JQuery UI Autocomplete With ID
JQuery UI
auto-complete widget is great.
Basically it just works and is very easy to customize.
The Problem
By default this control supports the retrieval of Text and Value for the selected item but still needs one tweek or two.
What I’m about to show here is how to:
- Use the basics of the control
- Use and store the item ID
- Don't show the ID on the textbox while selecting an item
The Basics
The basic idea is to pass a json array of strings and it will do the rest.
var req = ["item 1", "item 2", "item 3"];
$('#txtRequestor').autocomplete({ source: req });
Storing the selected item ID
In real world nothing is this simple and we usually have an ID for each item on the list. We may use this ID in several ways but the more obvious is to store the selected ID on the database.
This is still very simple, just feed the control some json objects instead of simple strings.
Note that each item must, at least have the following structure:
- label - Represents the display text
- value - Represents the item value (the ID in our case)
var req = [
{"label":"item 1", "value":1},
{"label":"item 2", "value":2},
{"label":"item 3", "value":3}];
$('#txtRequestor').autocomplete({
source: req,
change: function (event, ui) { alert(ui.item.value); } });
Using the change event we can handle the ID selected item ID and store it on a variable for later use.
Not showing the value (ID) on the textbox
If you tried the code above you got anoyed with the fact that the our ID is being shown on the rextbox while we select an item from the list. Didn’t you?! :)
To avoid this is very simple, we must only change our json object a little as follows.
var req = [
{"label":"item 1", "value":"item 1", "id": 1},
{"label":"item 2", "value":"item 2", "id": 2},
{"label":"item 3", "value":"item 1", "id": 3}];
$('#txtRequestor').autocomplete({
source: req,
change: function (event, ui) { alert(ui.item.id); } });
As you can see I just added a new property to each item for our id value. This will foul the control passing the same value as both display and value and have a “backup” property that holds the actual id value.