Wednesday, November 30, 2011

Using jQuery Autocomplete and processing the results yourself

The jQuery Autocomplete function can be added to an input text field. It enables users to quickly find and select from a pre-populated list of values as they type.
Using Ajax the source of an Autocomplete field can be a list of objects that is the result of a server-side method call. Normally we pass the values back to the Autocomplete processor, that shows them below the input field (as illustrated in this demo). In the following example I use the values to update a list of terms. Each term is rendered as a link (in a 'TermList' container DIV), that can be clicked to display the term's description. Though we must manipulate the browser DOM ourselves to display the results we still benefit from the Autocomplete's input functionality (that can be customized by setting properties).

<script type="text/javascript">
    $(document).ready(function () {
            source: function (request, response) {
                $.getJSON("term/search", { searchText: request.term },
                    function (data) {
                        var html = "";
                        $.each(data, function (index, term) {
                            html += "<p><a href='term/view/" + term.Id + "'>" +
                                term.Label + "</a></p>";
                        // Note: By not calling the Autocomplete's response function,
                        // the default menu popup behavior is disabled.
            minLength: 0,
            delay: 100
When the user starts typing in the input field, a list of terms starting with the characters typed is retrieved from the web server. Because the server-side method may access a database, the Autocomplete may respond rather slow. In a follow-up of this post a client-side cache will be introduced to save search results in the browser and show cached data if it is available.

No comments:

Post a Comment