I have an input box that uses jQuery autocomplete. I’d like to add a little functionality to the page so it can accept a value on page load and then select the top choice in the autocomplete list. I’ve created a jsfiddle to demonstrate what I mean:
http://jsfiddle.net/bwhitney/MQpQG/2/
Or here is just the code:
var myArray = ["apple - a ripe red fruit"
, "banana - yellow fruit grown in bunches"
, "orange - the name says it all"];
$("input#textbox").autocomplete({
source: myArray
});
$('#clickme').click(function() {
// select the #1 autocomplete option for the given text "apple"
// ???
});
With the html:
<input type="text" id="textbox" />
<input type="button" id="clickme" value="Set the value" />
So for example if the page loaded with the value “apple” then the text “apple – a ripe red fruit” should be loaded. Sending the entire phrase “apple – a ripe red fruit” is not a viable option in this case.
I could write a loop that iterates over each item in the array and parses out the first word, but I’m hoping jQuery has a better way of doing it since it can already get the correct answer at the top of its list.
Edit: Just to clarify, I figured if I can get it to work by pressing a button I can also get it to work by passing in a value when the page loads. That’s why my example uses a button instead of on page load.
It’s not much effort to write it yourself, and no matter how you look at it, you’re going to have to iterate over the array to find the item you’re looking for.
Demo