最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery autocomplete _renderItem is not working - Stack Overflow

programmeradmin3浏览0评论

_renderItem is not executing at all, tried with console.log too no messages printed. Tried with 'autocomplete', 'ui-autocomplete', 'Autocomplete' attributes no hope.

In addition I could not understand the purpose of "response with map functions", so disabled it.

$(document).ready(function () {

myVars.shId = $('#dataVar').attr('sh-data');

///// search ////// ,output
console.log(myVars.shId);
$('#name-list').autocomplete({

        source: function (request, response) {
            $.ajax({
                url: myVars.czbUrl,
                data: { searchText: request.term, maxResults: 10, shopId: myVars.shId },
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    /*response($.map(data, function (item) {
                        console.log(data);
                        return {

                            value: item.product_name,
                            avatar: item.pfimage_thumb,
                            rep: item.product_name,
                            selectedId: item.url
                        };
                    }))*/
                }
            })
        },
        select: function (event, ui) {

                             alert(ui.item ? ("You picked '" + ui.item.label)
                                                      : "Nothing selected, input was " + this.value);

            return false;
        }
    }).autocomplete( "instance" )._renderItem = function (ul, item) {
        console.log('test');
        /*var inner_html = '<a><div class="list_item_container"><div class="image"><img src="' + item.pfimage_thumb + '"></div><div class="label"><h3> Reputation:  ' + item.volume + '</h3></div><div class="description">' + item.product_name + '</div></div></a><hr/>';
        return $("<li></li>")
                .data("ui-autocomplete-item", item)
                .append(inner_html)
                .appendTo(ul);*/
    };

HTML:

 <script type="text/javascript" src=".2.0/jquery.min.js"></script>
  <script src=".12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery/ui/1.12.1/themes/base/jquery-ui.css">

<h4>search:<input type="text" id="name-list" /></h4>

_renderItem is not executing at all, tried with console.log too no messages printed. Tried with 'autocomplete', 'ui-autocomplete', 'Autocomplete' attributes no hope.

In addition I could not understand the purpose of "response with map functions", so disabled it.

$(document).ready(function () {

myVars.shId = $('#dataVar').attr('sh-data');

///// search ////// http://jsbin.com/xavatajiku/edit?js,output
console.log(myVars.shId);
$('#name-list').autocomplete({

        source: function (request, response) {
            $.ajax({
                url: myVars.czbUrl,
                data: { searchText: request.term, maxResults: 10, shopId: myVars.shId },
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    /*response($.map(data, function (item) {
                        console.log(data);
                        return {

                            value: item.product_name,
                            avatar: item.pfimage_thumb,
                            rep: item.product_name,
                            selectedId: item.url
                        };
                    }))*/
                }
            })
        },
        select: function (event, ui) {

                             alert(ui.item ? ("You picked '" + ui.item.label)
                                                      : "Nothing selected, input was " + this.value);

            return false;
        }
    }).autocomplete( "instance" )._renderItem = function (ul, item) {
        console.log('test');
        /*var inner_html = '<a><div class="list_item_container"><div class="image"><img src="' + item.pfimage_thumb + '"></div><div class="label"><h3> Reputation:  ' + item.volume + '</h3></div><div class="description">' + item.product_name + '</div></div></a><hr/>';
        return $("<li></li>")
                .data("ui-autocomplete-item", item)
                .append(inner_html)
                .appendTo(ul);*/
    };

HTML:

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<h4>search:<input type="text" id="name-list" /></h4>
Share Improve this question edited Jun 5, 2017 at 13:31 user3369417 asked Jun 5, 2017 at 8:47 user3369417user3369417 4181 gold badge6 silver badges17 bronze badges 5
  • putting your jquery-ui.js after jquery.min.js and check if any errors in console – Curiousdev Commented Jun 5, 2017 at 8:51
  • Yes it is like that, I misplaced it here., it is now corrected. – user3369417 Commented Jun 5, 2017 at 8:58
  • What does your data look like? Have you checked it's being delivered as expected? Most likely the renderMenu function is not firing because the response() callback receives nothing – blgt Commented Jun 5, 2017 at 9:42
  • I can see my the data in console.log(data) at success function, Is the response blocking renderItem?, If I enable response I get error like 'item.product_name is null, etc. – user3369417 Commented Jun 5, 2017 at 9:59
  • Got below error with response function enabled. "main.js:67 Uncaught TypeError: Cannot read property 'product_name' of null" – user3369417 Commented Jun 5, 2017 at 10:20
Add a comment  | 

3 Answers 3

Reset to default 12

A few small corrections and you should be on your way:

Example: https://jsfiddle.net/Twisty/3gm3sfem/

JavaScript

$(function() {
  var myData = [{
    product_name: "Name 1",
    pfimage_thumb: "thumb1.jpg",
    url: "url1"
  }, {
    product_name: "Name 2",
    pfimage_thumb: "thumb2.jpg",
    url: "url2"
  }, {
    product_name: "Name 3",
    pfimage_thumb: "thumb3.jpg",
    url: "url3"
  }];
  $('#name-list').autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "/echo/json/",
        data: {
          json: JSON.stringify(myData)
        },
        dataType: "json",
        type: "POST",
        success: function(data) {
          console.log(data);
          response(data);
        }
      })
    },
    select: function(event, ui) {
      alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);
      return false;
    }
  }).autocomplete("instance")._renderItem = function(ul, item) {
    console.log('test');
    var item = $('<div class="list_item_container"><div class="image"><img src="' + item.pfimage_thumb + '"></div><div class="label"><h3> Reputation:  ' + item.volume + '</h3></div><div class="description">' + item.product_name + '</div></div>')
    return $("<li>").append(item).appendTo(ul);
  };
});

If your data is coming back, pass it to response() to ensure that the menmu get rendered. You do not need <a> since select will be fired either way.

i wanted to set _renderItem and _renderMenu, so i came across the following example:

$(document).ready(function() {
        var products = $(".products").clone();
        $('#search-box').autocomplete({
            minLength: 1,
            source: function(request, response){
                $.ajax({
                    url:"../ajax-search.php",
                    dataType:"json",
                    html: true,
                    data:{term:request.term},
                    success: function(data){
                        response(data.slice(0,5));
                    }
                });
            },
            create: function (event,ui){
               $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
                return $('<li>')
                    .append("<img src=../images/"+item.Image +" alt='img' />")
                    .append('<a>' + item.Number  + '<br>' + item.Name  + '</a>')
                    .appendTo(ul);
            };
               $(this).data('ui-autocomplete')._renderMenu = function () {
                    this.menu.element.css({
                    width: $('#search-box').width(),
                    border: 'medium solid'
                });

            };
        }
        });

if found this answer here

You need to use Jquery widget factory to extend autocomplete object. It is explained in these articles:

https://learn.jquery.com/jquery-ui/widget-factory/extending-widgets/

it worked like this:

you add your widget code like this:

$.widget(
"custom.superAuto",
$.ui.autocomplete,
{
    _renderMenu : function(ul, items) {
        var self = this;
        ul.append("<div><span style='float:left; width: 50%; border-top:none; color:#949494;font-family:arial;font-size:14px' id='products'>KOSSSS</span></div>");
        $.each(items, function(index, item) {
        self._renderItem(ul.find("#products"),item);
        });
    },
    _renderItem: function (column, item)
    {
        return $("<li style='text-align:left; font-size:12px; height:28px'>")
    }
});

The above code extends autocomplete object and you can use superAuto instead and use your custom logic to render your menu like this:

$(".suggestion-input").superAuto(
                {
                    minLength : 2,
                    source : function(request, response) {

                        $.get(encodeURI("http://127.0.0.1:8080/api/v1/search/" + request.term),
                                function(data) {
                                    response(data);
                                });

                    }
                    
                });
发布评论

评论列表(0)

  1. 暂无评论