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.


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

Good way to solve this in Jquery manner

$("#dropDownMenuKategorie option:selected").index()

You can use the .prop(propertyName) function to get a property from the first element in the jQuery object.

var savedIndex = $(selectElement).prop('selectedIndex');

This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:

$(selectElement).prop('selectedIndex', savedIndex);

I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.

var vOptionSelect = "#productcodeSelect1";

The index is returned with:

$(vOptionSelect).find(":selected").index();

try this

 alert(document.getElementById("dropDownMenuKategorie").selectedIndex);