jquery ui autocomplete _renderItem seems to interfere with select event
Asked Answered
C

1

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.

Coptic answered 5/6, 2012 at 15:39 Comment(0)
O
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:

Olodort answered 5/6, 2012 at 15:49 Comment(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.Lozar
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% widthIllaffected

© 2022 - 2024 — McMap. All rights reserved.