Search autocomplete ...? Jquery use possible?

Let's 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 the autocomplete feature so that if the user types in "apple" it will give them the option to select "apple" or "apple pear" from the dropdown menu and fill out the form text field when you click on It? Like Google, for example, offers tips when trying to type something.

I thought I wanted to use 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 complete code, but the last time I posted all my code it was too much to read, so I created this to give an example of what I am trying to do.

+3


source to share


2 answers


You are on the right track. The jQuery UI autocomplete widget uses an array of items to select. We can use jQuery's map method to map a database object to an array of keys and then use that as an autocomplete source.

 <form name="searchForm">
   <input type="text" id="Fruit" name="getFruit"/>
 </form>

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");

var source = $.map(database, function(val, i) {
  return i;
});

$( "#Fruit" ).autocomplete({
      source: source
});

      



Try it on jsFiddle!

+5


source


Twitter Bootstrap has this nice jQuery plugin that does it for you: http://twitter.github.com/bootstrap/javascript.html#typeahead

Just use

$( element ).typeahead( { source: arrayOrFunction } );

      



This is well documented, so you should understand it. =)

JQuery UI autocomplete does it in a similar way too. Just pass an array of strings or a function that takes the request as the first parameter and a callback as the second and invokes the callback with autocomplete parameters.

0


source







All Articles