Paul Tomblin
Paul Tomblin

Reputation: 182782

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.

Upvotes: 4

Views: 3126

Answers (2)

Paul Tomblin
Paul Tomblin

Reputation: 182782

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();
  }
}

Upvotes: 6

Peter.B
Peter.B

Reputation: 33

Many thanks for this, it works well for us. In case it helps anyone, I had problems with it when first using it under IE10. It had always worked fine in IE8, Chrome and Firefox.

Under IE10 it failed on the jQuery(this).data('autocomplete').menu.element.children() line with: Member not found

This turned out to be simply because the web page had: <meta http-equiv="X-UA-Compatible" content="IE=7"/> Removing this fixed the problem (and it still works fine in IE8).

But before I noticed this I spent a lot of time trying and failing to move to jquery-1.11.1.min.js (from 1.6.4) and jquery-ui-1.11.0 (from 1.8.16).

Upvotes: 0

Related Questions