Lets say I have the following code:
HTML:
<form name="searchForm">
<input type="text" id="Fruit" name="getFruit"/>
</form>
Javascript:
function Fruit(name, color){
this.name = name;
this.color = color;
};
var database = {};
database['banana'] = new Fruit("Banana", "Yellow");
database['apple'] = new Fruit("Apple", "Red");
database['orange'] = new Fruit("Orange", "Orange");
database['apple pear'] = new Fruit("Apple Pear", "Green");
How can I use an autocomplete function so that if the user types “apple”, it will give them an option to select “apple” or “apple pear” from a drop down menu and populate the form textbox when you click on it? Kind of how like google gives suggestions when you try to type something.
I was thinking I want to use the jquery http://jqueryui.com/autocomplete/ but I’m not sure how to implement it.
$( "#Fruit" ).autocomplete({
source: database // How would you implement this?
});
This is not my full code, but last time I posted all my code it was too much to read so I created this to give just an example of what I’m trying to do.
You are on the right track. jQuery UI’s autocomplete widget takes in an array of items to choose between. We can use jQuery’s map method to map your database object to an array of keys and then use that as the autocomplete source.
Try it out on jsFiddle!