I’m looking into using the jQuery UI autocomplete widget to implement user lookup by first or last name. It looks like by default autocomplete looks up words by character sequence no matter its occurrence in a word. So if you have data such as: javascript, asp, haskell and you type in 'as' you will get all three. I would like it to only match beginning of the word. So in above example you get only 'asp'. Is there a way to configure the autocomplete widget to do this?
Ultimately it would be even better to match by beginning of first or last name like it is in Gmail.
Note: I’m trying to figure out a way to do this using the jQuery UI widget specifically. Since I’m already using jQuery UI in my project, I’m planning to stick with it and try not adding additional libraries to my web application.
In jQuery UI v1.8rc3, the autocomplete widget accepts a source option which can be either a string, an array, or a callback function. If it’s a string, autocomplete does a GET on that URL to get options/suggestions. If an array, autocomplete does a search, as you pointed out, for the presence of the typed chars in any position in the terms of the array. The final variant is what you want – the callback function.
From the autocomplete documentation:
Example code:
A few key points:
$.ui.autocomplete.escapeRegex(req.term);That escapes the search termso that any regex-meaningful terms in the text typed by the user are treated as plain text. For example, the dot (.) is meaningful to regex. I learned of this escapeRegex function by reading the autocomplete source code.
new Regexp(). It specifies a regexp beginning with ^ (Circumflex), which implies, it will match only when the typed characters appear at the beginning of the term in the array, which is what you wanted. It also uses the "i" option which implies a case-insensitive match.$.grep()utility just calls the provided function on each term in the provided array. The function in this case simply uses the regexp to see if the term in the array is a match for what was typed.working demo: http://jsbin.com/ezifi
what it looks like:
Just a note: I find the documentation on autocomplete to be pretty immature at this point. I didn’t find examples that did this, and I couldn’t find working doc on which .css files were necessary or which .css classes would be used. I learned all this from inspecting the code.
See also, how can I custom-format the Autocomplete plug-in results?