0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry , I deleted my original comment before I saw your jFiddle. It does work, but I just think it needs to be clear to the developer how to access it. The jFiddle you show accesses a generic 'option' element, but if there is more than one option element, it concatenates all results together. What I 'think' the original post aimed at was getting the id of a selected element, which is something like ("#my_selector :selected").attr("id"); ....unless I'm mistaken or mis-read, which is entirely possible.
@Shem: Yes, of course, but I expect someone using .text to know this. The documentation says "Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements." If you want the text of a specific (single) element, you have to only select that one. But yeah, I agree that I didn't show how to get the selected option.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.