jQuery
jQuery Get Selected Index Examples – 2 Ways
At times, it could be very useful to use jQuery to Get Selected Option Index value for carrying out relevant processing. In this article, I am going to show you a very easy and simple way to get selected option index value using jQuery. And the actual code is just 1 line, so it’s super easy to follow and implement.
Examples to Get Selected Option Index using jQuery
Let’s assume that you have a select dropdown with ID “countries”. To get the index of the selected option, you can use any of the following 2 methods:
Method 1: By using the ‘ID’ of the select dropdown:
$("#countries option:selected").index();Method 2: By using the ‘name’ of the select dropdown:
$("select[name='countries'] option:selected").index();Example: Get Selected Option Index using jQuery
<html>
<head>
<title>Examples to use jQuery to Get Selected Option Index</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<select name="countries" id="countries">
<option value="Australia">Australia</option>
<option value="London">London</option>
<option value="USA">USA</option>
</select>
<input type="submit" name="get" id="get" value="Get selected index" />
<script type="text/javascript">
$('#get').click(function() {
//Method 1
alert( $("#countries option:selected").index() );
//Method 2
alert( $("select[name='countries'] option:selected").index() );
});
</script>
</body>
</html>Very simple, isn’t it?
Do you know of any other ways to use jQuery to get selected index / get selected option index ? Feel free to suggest by commenting below.
It is not working for me.
alert($(“#myselect option:selected”).index();
the above shows -1.
July 30, 2012 at 11:08 am
Hi Jojo,
It’s not working because you probably don’t have the html select dropdown on the page or you are using incorrect ID. In your code, you are using #myselect. This means that your HTML select dropdown MUST have an ID of myselect. Unless this is fixed, it won’t work.
In order to help you, I have added a complete example that shows you exactly how to do it. Just refer to the example above and try it out & let me know how that goes.
Robert
July 30, 2012 at 2:08 pm