08 March 2012

The jQuery UI documentation for autocomplete doesn’t do the greatest job of clarifying how to override the select() and focus() methods. There is mention of ‘Cancelling this event’, but they only snuck in how to do the cancelling in the search() method. This led to considerable confusion on my part, where code like this:

    $(document).ready(function() {  
      $('#foo').autocomplete({ 
        source: '/bar',
        select: function(event, ui) {   
          $('#selector').val(ui.item.label);    
          $('#target').val(ui.item.value);
        },
      });
    });
    

Would lead to the maddening result of those changes being applied, then overwritten by the default behavior of the method.

The simple solution is to add a return false; to the end of your custom implementation:

    $(document).ready(function() {  
      $('#foo').autocomplete({ 
        source: '/bar',
        select: function(event, ui) {   
          $('#selector').val(ui.item.label);    
          $('#target').val(ui.item.value);
          return false;
        },
      });
    });
    

This prevents the default code for the method from running.