Is there a way of getting the attribute - such as 'rel' from the selected option of the 'select' tag - i.e.?
<select name="menu" id="menu">
<option value="1" rel="123">Option 1</option>
<option value="2" rel="124">Option 2</option>
</select>
Any idea?
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.
jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.
You can just use the :selected
filter.
Here's a fiddle : http://jsfiddle.net/jomanlk/ECAea/
$('#menu').change(function(){
alert($(this).find('option:selected').attr('rel'));
});
with jQuery
$('#menu option:selected').attr('rel');
with javascript
var sel = document.getElementById('menu');
var option = sel.options[sel.selectedIndex];
var rel = option.getAttribute('rel');
demo with both versions at http://jsfiddle.net/gaby/WLFmv/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With