10

My select event doesn't work if I use _renderItem. If I comment out the last block of code where I call _renderItem, the select event works. When I use _renderItem, the select event doesn't fire at all.

var cache = {}, lastXhr; 

$("#hifind-find").autocomplete({
  source: function(request, response) {

    var term = request.term; 
    if (term in cache) {
      response(cache[term]);
      return;
    }

    var posturl = '/hifind/jquery_ui/autocomplete/'+term; 
    lastXhr = $.post(posturl, function(data, status, xhr) {
      cache[term] = data; 
      if (xhr === lastXhr) {
        response(data); 
      } 
    }, 'json');
  },
  delay: 300,
  minLength: 1,
  select: function(event, ui){
    window.location = ui.item.dest;
  }
});

$.ui.autocomplete.prototype._renderItem = function(ul, item) {
  return $("<li></li>")
    .data("item.autocomplete", item)
    .append('<img src="' + iconImgPath + item.flag + '-search.png" class="icon-autocomplete-bundle">' + item.label )
    .appendTo( ul );
};

I get the same result if I do something like...

$("#hifind-find").autocomplete(myConfig).data("autocomplete")._renderItem = renderItemFunction;

Either way, the select doesn't fire. _renderItem does what it's supposed to. It modifies the item and there are no errors, but it seems to break the select.

1 Answer 1

14

I believe this is because you are not wrapping the item in an anchor (a) tag. Update your code to wrap the img in an anchor and it'll work fine:

$.ui.autocomplete.prototype._renderItem = function(ul, item) {
  return $("<li></li>")
    .data("item.autocomplete", item)
    .append('<a><img src="' + iconImgPath + item.flag + '-search.png" class="icon-autocomplete-bundle">' + item.label + '</a>')
    .appendTo( ul );
};

Here are some examples that might help:

2
  • 2
    The sad thing is that the official documentation for jQuery UI not only completely omits this, but they actually tell you to do the wrong thing. Here's their example code for _renderItem: $( "<li>" ) .attr( "data-value", item.value ) .append( item.label ) .appendTo( ul ); (note the lack of an <a>). Thank goodness for this answer. Mar 18, 2016 at 17:24
  • Moreover, as now of UI 1.12.* it's better to place a container <div> instead of the <a> as it will has a 100% width Jul 5, 2017 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.