Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery autoComplete view all on click?

I'm using jQuery's autocomplete in a relatively simple way:

$(document).ready(function() {
  var data = [ {text: "Choice 1"}, 
               {text: "Choice 2"}, 
               {text: "Choice 3"} ]

$("#example").autocomplete(data, {
  matchContains: true,
  minChars: 0,
  formatItem: function(item) 
    { return item.text; }
    }
  );
  });

How do I add an onclick event (like a button or a link) that will display all the available choices for the autocomplete? Basically I'm looking to make a hybrid of an autocomplete and a select/dropdown element.

Thanks!

like image 897
Rio Avatar asked Aug 12 '09 20:08

Rio


3 Answers

You can trigger this event to show all of the options:

$("#example").autocomplete( "search", "" );

Or see the example in the link below. Looks like exactly what you want to do.

http://jqueryui.com/demos/autocomplete/#combobox

EDIT (from @cnanney)

Note: You must set minLength: 0 in your autocomplete for an empty search string to return all elements.

like image 67
Tom Pietrosanti Avatar answered Nov 10 '22 12:11

Tom Pietrosanti


I found this to work best

var data = [
    { label: "Choice 1", value: "choice_1" },
    { label: "Choice 2", value: "choice_2" },
    { label: "Choice 3", value: "choice_3" }
];

$("#example")
.autocomplete({
    source: data,
    minLength: 0
})
.focus(function() {
    $(this).autocomplete('search', $(this).val())
});

It searches the labels and places the value into the element $(#example)

like image 40
Craig Avatar answered Nov 10 '22 14:11

Craig


I can't see an obvious way to do that in the docs, but you try triggering the focus (or click) event on the autocomplete enabled textbox:

$('#myButton').click(function() {
   $('#autocomplete').trigger("focus"); //or "click", at least one should work
});
like image 20
karim79 Avatar answered Nov 10 '22 13:11

karim79