[jquery] 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.

This question is related to jquery html select indexing

The answer is


selectedIndex is a JavaScript Select Property. For jQuery you can use this code:

jQuery(document).ready(function($) {
  $("#dropDownMenuKategorie").change(function() {
    // I personally prefer using console.log(), but if you want you can still go with the alert().
    console.log($(this).children('option:selected').index());
  });
});

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

try this

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

You can get the index of the select box by using : .prop() method of JQuery

Check This :

<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

});

function check(){
    alert($("#NumberSelector").prop('selectedIndex'));
    alert(document.getElementById("NumberSelector").value);
}
</script>
</head>

<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
    <option value="Its Zero">Zero</option>
    <option value="Its One">One</option>
    <option value="Its Two">Two</option>
    <option value="Its Three">Three</option>
    <option value="Its Four">Four</option>
    <option value="Its Five">Five</option>
    <option value="Its Six">Six</option>
    <option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>

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

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Examples related to indexing

numpy array TypeError: only integer scalar arrays can be converted to a scalar index How to print a specific row of a pandas DataFrame? What does 'index 0 is out of bounds for axis 0 with size 0' mean? How does String.Index work in Swift Pandas KeyError: value not in index Update row values where certain condition is met in pandas Pandas split DataFrame by column value Rebuild all indexes in a Database How are iloc and loc different? pandas loc vs. iloc vs. at vs. iat?