Search code examples
jquery-uijquery-ui-autocomplete

jquery-ui autocomplete selecting the only answer


I want to have jquery-ui autocomplete automatically select the answer if there is only one answer that comes back.


Solution

  • I set up the autocomplete with an "open" callback:

        $('#people_new_user input[type="text"]').each(
        function(index, element) {
            var field = element.name;
            $(element)
                .autocomplete({
              source: "/cf/AutoComplete/People?current="+field,
              open: openUser
            });
        });
    

    And in the open callback I look to see if there is only one result, and select it if it is:

    function openUser(event, ui)
    {
      // Try to select the first one if it's the only one
      var $children = $(this).data('ui-autocomplete').menu.element.children();
      if ($children.size() == 1)
      {
         $children.first().click();
      }
    }