user398341
user398341

Reputation: 6577

jQuery - select tag - get attribute of the selected element

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?

Upvotes: 8

Views: 25560

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195962

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/

Upvotes: 5

JohnP
JohnP

Reputation: 50009

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

Upvotes: 15

verdesmarald
verdesmarald

Reputation: 11866

You can use .attr("attributeName") to get the value of attributes. See .attr().

To find the selected option you can use $('#menu option[selected=true]') or similar.

Upvotes: 1

Related Questions