wuyuntao / jquery-autosuggest

A fork of AutoSuggest jQuery plugin writtern by Drew Wilson.
http://github.com/wuyuntao/jquery-autosuggest
118 stars 59 forks source link

jQuery AutoSuggest Plugin

A fork of AutoSuggest jQuery plugin writtern by Drew Wilson.

http://code.drewwilson.com/entry/autosuggest-jquery-plugin

How It Works

AutoSuggest will turn any regular text input box into a rad auto-complete box. It will dynamically create all the HTML elements that it needs to function. You don't need to add any extra HTML to work with AutoSuggest. Also, AutoSuggest uses ZERO images! All styling is done 100% in the included CSS file. This means it is super easy to customize the look of everything! You only need to edit the included CSS file. You can even use images if you want, just add the appropriate lines of code into the CSS file.

As you type into the AutoSuggest input box, it will filter through it's Data and "suggest" matched Data items to you. You can pass in an Object of Data to AutoSuggest or you can have it call a URL as you type to get it's Data from. AutoSuggest will display the matched Data items in a selectable list, which is 100% customizable. You have the option of structuring the HTML elements of that list however you want via the formatList callback function. You case an example of this in the second example above.

When you type into the input box and the "suggestion" dropdown list appears, a few things happen:

The plugin expects the Data passed into it (or gathered from the URL) to be formatted in JSON. JSON is an extremely easy format to work with, and if you don't already... you should :) To learn more about JSON, check out my post/video, An Introduction to JSON.

When an AJAX request is made the search string is sent over in a param named "q" by default. However you can change that name with the queryParam option. Here is a default example AJAX request: http://www.mysite.com/your/script/?q=mick "mick" would be the search query that was typed into the input box. Be sure to setup your server-side code to grab that param and send back some results.

As of AutoSuggest version 1.4 you can now create selections by using the tab or comma keys. To do this simply type something into the box and hit the tab or comma keys. The selection is added to AutoSuggest in the exact same manner as if it were chosen from the Results dropdown.

AutoSuggest has been tested (and works) in: IE7 & IE8, Firefox, Safari, Opera, and Chrome.

How To Use It

Obviously you need to make sure you have the latest jQuery library (at least 1.3) already loaded in your page. After that it's really simple, just add the following code to your page (make sure to wrap your code in jQuery's ready function):

$(function(){
    $("input[type=text]").autoSuggest(data);
});

The above line of code will apply AutoSuggest to all text type input elements on the page. Each one will be using the same set of Data. If you want to have multiple AutoSuggest fields on your page that use different sets of Data, make sure you select them separately. Like this:

$(function(){
    $("div.someClass input").autoSuggest(data);
    $("#someID input").autoSuggest(other_data);
});

Doing the above will allow you to pass in different options and different Data sets. Below is an example of using AutoSuggest with a Data Object and other various options:

var data = {items: [
    {value: "21", name: "Mick Jagger"},
    {value: "43", name: "Johnny Storm"},
    {value: "46", name: "Richard Hatch"},
    {value: "54", name: "Kelly Slater"},
    {value: "55", name: "Rudy Hamilton"},
    {value: "79", name: "Michael Jordan"}
]};
$("input[type=text]").autoSuggest(data.items, {selectedItemProp: "name", searchObjProps: "name"});

Below is an example using a URL to gather the Data Object and other various options:

$("input[type=text]").autoSuggest("http://mysite.com/path/to/script", {minChars: 2, matchCase: true});

The "value" property will be stored (comma separated) in the hidden input field when chosen from the "suggestion" dropdown list. You can see an example of the "value" property being set for each data item in the example above. Typically the "value" property would contain the ID of the item, so you can send a list of "chosen" IDs to your server.

Below is an example of how to process the data sent via AJAX to your server in PHP:

<?php
    $input = $_GET["q"];
    $data = array();
    // query your DataBase here looking for a match to $input
    $query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
    while ($row = mysql_fetch_assoc($query)) {
        $json = array();
        $json['value'] = $row['id'];
        $json['name'] = $row['username'];
        $json['image'] = $row['user_photo'];
        $data[] = $json;
    }
    header("Content-type: application/json");
    echo json_encode($data);
?>

If the available data will change (e.g. if you progressively or asynchronously load more data for autosuggesting), you can pass a function to autosuggest as the data source.

$(function() {
    var slowly_loaded_data = {items: []};

    // Obviously, you'd do something more interesting here.
    setTimeout(function() { slowly_loaded_data = {items: [{value: '11', name: 'A name'}]}; }, 2000);

    function get_data(query, next) {
        next(slowly_loaded_data, query);
    };
    $("input[type=text]").autoSuggest(get_data);
});

The function will be passed two arguments:

Options

The formatList option will hand you 2 objects:

In order to add extra things to the 'result' item (like an image) you will need to make sure you pass that data into AutoSuggest. Below is an example of formatList in action:

formatList: function(data, elem){
    var my_image = data.image;
    var new_elem = elem.html("add/change stuff here, put image here, etc.");
    return new_elem;
}

You MUST return the HTML object. formatList will run on each 'result' item.

License

AutoSuggest is dual licensed under the MIT and GPL licenses.

Authors

Originally developed by Drew Wilson

Contributors