jQuery Autocomplete with a Hidden Value
Tuesday, June 02 2009 3 Comments
A number of people commented on my post about a jQuery Autocomplete Textbox in ASP.NET MVC wanting to know how to provide a value for the items being displayed. It’s not an uncommon request. For many pieces of data you’ll have display values as well as unique identifiers to distinguish & provide reference to the items.
Unfortunately it’s not well document, however this is fully supported with Dylan Verheul’s jQuery autocomplete plugin.
The first step is to separate your display names from the values in your result from the server. We were retuning cities before, like this:
HOUSTON, AK HOUSTON, AL HOUSTON, TX HOUCK, AR HOUGHTON, IA
The individual items are separated by a new line character. In order to provide a value for each of these, you have to separate the item with a pipe “|”.
HOUSTON, AK|456 HOUSTON, AL|1245 HOUSTON, TX|553 HOUCK, AR|99 HOUGHTON, IA|401
If your display items might contain a pipe character, then you’ll have to change the separator setting for the plugin. You can do by providing the option cellSeparator.
Now that our items have a value coming back from the server, how can we retrieve it when an item is selected? That is done via the onSelectItem function. This is a callback that will send you the formatted <li> tag. If there was a value specified, it will be placed in the extra attribute.
Here’s an example:
$(cities).autocomplete(action_url, {
lineSeparator: '\n',
cellSeparator: '|',
onItemSelect: function(li) { if(li.extra) alert("You selected " + li.extra[0]); }
});
I’ve specified the options for lineSeparator and cellSeparator. These are the default values, but you can easily change them if the character is a valid portion of the text being returned by the server.
You can use this handler to place the selected value in a hidden field to save it for a form submission.
Hope this helps! For more information, I suggest you read the source code and examine the plugin page source for more examples.


Nathan B
6.16.2009
3:45 PM
Thats a great, basic way to do things. The trouble usually comes in edge cases resulting from when the handler is actually called. There are a few ways that slip through the cracks, and allow data to be placed in the autocomplete input without finding their way into the hidden fields, resulting in null input serverside on the form submit, if the hidden fields aren't validated.