I have a "questionairre" that is made up of a series of select boxes.
I need to use two properties in the options. For each selected option I need the value (which I know how to get and is working fine) but I also need to store an additional value which represents the id of the specific option in a DB.
One solution would be to put the two values in the "value" property and parse it out, but if there is some ot开发者_StackOverflowher property I can use that might be easier and clearer. Can I add a custom property like databaseId
that could be accessed with jQuery?
I would not add custom attributes as this would not be valid HTML anymore.
Can't you use the "normal" ID attribute (i.e. the one that any HTML element has) of these option
elements?
You could also prefix the ID if it is necessary and take a substring of the ID, e.g.
<option id="db23123" value="value">Value</option>
Or depending how your select
is structured, you could also use the value
attribute for the database ID and put the other "value" as text inside the option (if it is human readable):
<option value="23123">Human Readable Value</option>
Then you can get the DB ID via .val()
and the text value via .text()
.
Another solution that works if you e.g. create the option
elements dynamically via JavaScript is to use the .data()
functionality. This allows you to attach arbitrary key-value pairs to any DOM node.
You could use the metadata-plugin.
You could then use like so:
Markup:
<select>
<option class="{db_id: 1}" name="X" value="y" selected="selected">
[...]
</select>
Script:
var data = $('option:selected').metadata();
alert(data.db_id);
精彩评论