views:

91

answers:

2

Hi All, 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 other property i can use that might be easier and clearer.. can i add a custom property?? like databaseId that could be accessed with jQuery?

thanks for ANY suggestions.

+1  A: 

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.

Felix Kling
A: 

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);
PatrikAkerstrand