What is the best way to keep track of the id of an element selected from an auto-suggest textbox?
I have an auto-suggest textbox. A user can either pick an already existing item in the databas开发者_开发问答e 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)?
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.
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.
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>
.
精彩评论