Hi. I've just started using jQuery Autocomplete a few weeks ago.

While using jQuery, I found that I needed to know how many records
were returned and also if the result set returned was empty. After
searching the jQuery documentation I couldn't find any property or
method that returned this value, so I've added that functionality
myself and wanted to share it with the group.

1) Determine the number of records returned:

I wanted to show the user how many results were returned after they
start typing into the autocomplete field similar to how Google
indicates the number of results found when you start typing in the
search box.

At first I thought the max parameter in the function formatItem
returned this value. However, it returns the max option that you set
it to. So if your query returns 100 records and you set max to 25,
it'll obviously return 25 (not what I wanted).

So after trying various things, I looked at the jQuery code and simply
added the number of records returned by the database to the
formateItem function. In the fillList() function around line 660 I
added the data.length parameter:

        var formatted = options.formatItem(data[i].data, i+1, max, data
[i].value, term, data.length);

And in my autocomplete code, I added the parameter to the end of the
param list:

        formatItem: function(data, i, total, value, searchTerm, totalResults)

So now whenever a new search is preformed, I get back the number of
search result from the database.

2) Determine if a result set returned was empty

I wanted to update a <div> with a message like "no records found"
whenever the query yielded no results. Again, after searching the
jQuery documentation, I couldn't find any property or method that
would indicate this so I added it to the code.

In the request function after the line var data = cache.load(term); I
added the following:

        if (!data) {
                options.isEmpty(0);
        } else {
                options.isEmpty(data.length);
        }

And in my autocomplete code, I added the following:

        isEmpty: function(data) {
                if (data == 0) {
                        $("#result").html("No match found");
                }
        }


Hope this helps others. Since I am new to jQuery I'd appreciate any
feedback especially if there is a better way to do this.

Thanks
John

Reply via email to