Fixing jQuery UI Autocomplete

jQuery UI 1.8 was recently released and it included a much needed autocomplete widget. For the most part, this widget works fine, but there is an annoying bug that makes it not quite ready for a production environment. Basically, if a user clicks on an option and doesn't release the mouse button fast enough, the option is not selected. You can see the bug in action on the jQuery UI autocomplete demo.

Thankfully, there is a workaround.

Here is what we would like to be able to do:

$("#autocomplete").autocomplete({
   source: 'search.php',
   select: function(event, ui) {
      alert(ui.item.id);
   }
});

Here is the bug-fixed version I came up with:

//global variable that stores the last focused option
var search_option = false;

$("#autocomplete").autocomplete({
   source: 'search.php',
 
   //when an item is focused, store item in the global variable
   focus: function(event, ui) {
      search_option = ui.item;
   },
 
   //when an item is selected with the keyboard, trigger
   //the mouse down event for consistency
   select: function(event, ui) {
      search_option = ui.item;
      $("#autocomplete").autocomplete('widget')
      .trigger('mousedown.choose_option');
   }
})

//bind the select event to mousedown
.autocomplete('widget').bind('mousedown.choose_option',function() {
   //immediately closes autocomplete when option is selected
   $("#autocomplete").autocomplete('close');
 
   //perform desired action
   alert(search_option.id);
});

Obviously, this isn't a very elegant solution, but I didn't want to mess around with the actual autocomplete code. Hopefully, this is fixed in the next release. Until then, this will have to do.