Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ui autocomplete _renderItem seems to interfere with select event

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.

like image 293
arnoldbird Avatar asked Jun 05 '12 15:06

arnoldbird


1 Answers

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:

  • Example without including an a tag in the markup generated in _renderItem (select is broken here like in your question): http://jsfiddle.net/MaLqe/

  • Example with an a tag in the generated markup: http://jsfiddle.net/3zSMG/

like image 100
Andrew Whitaker Avatar answered Oct 20 '22 22:10

Andrew Whitaker