I have an auto-suggest textbox. A user can either pick an already existing item in the database of type in a new one.
How do i keep track of the id if item was selected (Store the id of the list of items coming from the db)?
I have an auto-suggest textbox. A user can either pick an already existing item in the database of type in a new one.
How do i keep track of the id if item was selected (Store the id of the list of items coming from the db)?
I would assign the ID of the existing item to a hidden <input>
element. When posting the form, you could first check for a value in the hidden <input>
element. If there isn't one, use the value from the other text <input>
.
The best choice depends upon the context. There are many ways to do this.
As Jordan suggested, use the <input type="hidden" ...>
in a form, especially if the value will be submitted via a form.
Store the value in in a javascript var
or object
.
There is jQuery's Data Cache. This is a simple key value store.
$("body").data("key","foo");
$("body").data("key"); // returns "foo"
And you could store the value in a cookie.
Which might make sense if you want the value to persist.
When you load the items from the DB, load it as a JSON string, so both the values and their associated IDs are passed into your javascript. You can even index it by the value:
var index = {};
index["some value"] = "some_id";
Then, when you are going to submit to the DB again, just reference for the ID.