Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
user398341 Avatar asked May 10 '11 08:05

user398341


People also ask

How do you get the selected value of an element?

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.

How get data attribute value in jQuery?

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" ).

How do I get the text value of a selected option jQuery?

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.

What is ATTR jQuery?

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.


2 Answers

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'));
});
like image 79
JohnP Avatar answered Oct 28 '22 08:10

JohnP


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/

like image 32
Gabriele Petrioli Avatar answered Oct 28 '22 09:10

Gabriele Petrioli