开发者

jQuery autosuggest example

I need to implement an "autosuggest" feature on our site but it needs to re-query the on every keystroke after a certain number of keys (like every character after 2 it would need to query again). So the result isn't a limiting search. For example, the autocomplete plugins I've seen work like the following:

[looking for a county] 1. customer types 'CA' and the first result would return 'Canada', 'Cambodia', and 'Camaroon' 2. customer continues to type and hits 'M' the new results 开发者_C百科would query within the only the existing 3 results (producing results of just 'Cambodia' and 'Camaroon')

I need a solution that would be the equivalent of querying my datasource on each keystroke. I already have the ajax call that will return my results based on the "typed" params. For example (in the above example), it would need to make an ajax call passing 'ca' first and if the customer kept typing passing 'can' on the 3 character and so forth.

Thanks.


The jQuery UI autocomplete plugin will do what you want.

See this demo http://jqueryui.com/demos/autocomplete/#remote-jsonp

the code for the demo:

$("#city").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "http://ws.geonames.org/searchJSON",
                    dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        name_startsWith: request.term
                    },
                    success: function(data) {
                        response($.map(data.geonames, function(item) {
                            return {
                                label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name
                            }
                        }))
                    }
                })
            },
            minLength: 2,
            select: function(event, ui) {
                log(ui.item ? ("Selected: " + ui.item.label) : "Nothing selected, input was " + this.value);
            },
            open: function() {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function() {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");


}
        });

You can use the download builder to get just the autocomplete example. As a bonus autocomplete is themeable and you can pick a themeroller ready theme or edit one and create your own.


jqueryui's autocomplete sends the full string each time, so you can do what you'd like to with it. You can also edit the events to save the last searching string and send that along with the new request, if that helped.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜