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.
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.
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.
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.
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”).
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);
Since version 1.6 jQuery has the prop
method that can be used to read properties:
alert($("#dropDownMenuKategorie").prop('selectedIndex'));
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