Populating a Hidden ID Field When Using the jQuery UI Autosuggest Widget
Posted 15 July 2011
The service that is called by the jQuery autosuggest widget returns a simple JSON object which contains an array of “rows” with a first name, last name, and customer ID value. The key was adding the customerID value to the autosuggest widget in the success event handler that’s part of the autosuggest widget setup:
One quick side note: the autosuggest control uses the value “term” as the name of the field it’s going to pass to the URL defined in the setup. If your service or server-side handler expects a variable named something other than “term,” you have to make this change in the data object in the autosuggest setup. In my example, my service expects a string with the name “searchString.” So in the data object in the setup, I’m telling the autosuggest control to pass the “term” value to my service with the name “searchString,” instead of “term.”
When an item is selected from the possible choices in the autosuggest widget, the “select” event is called. That’s where you can grab the customerID of the person who was selected. It’s really simple to do this:
The ui.item object contains all of the data that you mapped out in the success event handler of the autosuggest control. I’m simply grabbing the ui.item.customerID value and assigning that to a hidden form field in the form called customerID. When the form is submitted, the customerID value is used for processing, rather than the string value of the selected person’s name in the text input.
I wasn’t able to find this particular (and, I think, common) use case in the jQuery UI docs, so hopefully it will be of help to someone!