Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  14] [ 1]  / answers: 1 / hits: 198548  / 14 Years ago, thu, december 30, 2010, 12:00:00

Very simple question I hope.



I have the usual <select> box like this



<select id=select>
<option value=1>this</option>
<option value=2>that</option>
<option value=3>other</option>
</select>


I can get the selected value (by using $(#select).val()) and the selected item's display value (by using $(#select :selected).text().



But how can I store like an additional value in the <option> tag? I would like to be able to do something like <option value=3.1 value2=3.2>other</option> and get the value of the value2 attribute (which would be 3.2 in the example).


More From » jquery

 Answers
41

HTML Markup



<select id=select>
<option value=1 data-foo=dogs>this</option>
<option value=2 data-foo=cats>that</option>
<option value=3 data-foo=gerbils>other</option>
</select>


Code



// JavaScript using jQuery
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
var extra = selected.data('foo');
...
});
});

// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');


See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/

See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/



By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.


[#94439] Tuesday, December 28, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
morrismilom

Total Points: 230
Total Questions: 96
Total Answers: 114

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
;