Saturday, December 4, 2010

Get the index of selected item in drop down using java script or jquery

Sometimes you will need the index of the selected item in a select (drop down/list) dynamically. You can use the javascript or jquery code snippet to achieve this. This will give you the index of the selected item in the select box.This will give the zero based index of the option in a set of options. To get the index of the selected item in a drop down or a list box we can use the following javascript code,

var index=documet.getElementById('element_id'). selectedIndex;

The same can be done using jquery as,

var index=$("#element_id").attr("selectedIndex"); 

For e.g:- if the html code is like this,

<select id="my_select">
<option value="I loves you">I loves you</option>
<option value="I hates you">I hates you</option>
<option value="I like you">I like you</option>
<option value="I know you">I know you</option>
</select>

Then the javascript code will be like this,

var index=documet.getElementById('element_id'). selectedIndex;

and jquery like this,

var index=$("#element_id").attr("selectedIndex");

No comments:

Post a Comment