Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of selected option with jQuery

I'm a little bit confused about how to get an index of a selected option from a HTML <select> item.

On this page there are two methods described. However, both are always returning -1. Here is my jQuery code:

$(document).ready(function(){     $("#dropDownMenuKategorie").change(function(){         alert($("#dropDownMenuKategorie option:selected").index());         alert($("select[name='dropDownMenuKategorie'] option:selected").index());     }); }); 

and in html

(...) <select id="dropDownMenuKategorie">     <option value="gastronomie">Gastronomie</option>     <option value="finanzen">Finanzen</option>     <option value="lebensmittel">Lebensmittel</option>     <option value="gewerbe">Gewerbe</option>     <option value="shopping">Shopping</option>     <option value="bildung">Bildung</option> </select> (...) 

Why this behavior? Is there any chance that the select is not "ready" at the moment of assigning its change() method? Additionally, changing .index() to .val() is returning the right value, so that's what confuses me even more.

like image 971
Valentino Ru Avatar asked Nov 26 '12 00:11

Valentino Ru


People also ask

How to get index of item in jQuery?

index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector. If the element is not found, . index() will return -1.

How to use index in jQuery?

The index() is an inbuilt method in jQuery which is used to return the index of the a specified elements with respect to selector. Parameter: It accepts an optional parameter “element” which is used to get the position of the element. Return value: It returns an integer denoting the index of the specified element.

What is selectedIndex in Javascript?

selectedIndex is a long that reflects the index of the first or last selected <option> element, depending on the value of multiple . The value -1 indicates that no element is selected.

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).


Video Answer


1 Answers

The first methods seem to work in the browsers that I tested, but the option tags doesn't really correspond to actual elements in all browsers, so the result may vary.

Just use the selectedIndex property of the DOM element:

alert($("#dropDownMenuKategorie")[0].selectedIndex); 

Update:

Since version 1.6 jQuery has the prop method that can be used to read properties:

alert($("#dropDownMenuKategorie").prop('selectedIndex')); 
like image 109
Guffa Avatar answered Oct 18 '22 14:10

Guffa