Sunday, December 5, 2010

To get the number of items in a drop down dynamically

Sometimes you will be required to count the number of options in a select (list/drop down) dynamically. You can achieve this using the following java script or jquery code snippet. This will give you the total number of options in select input field in a form, that having a unique id. You can use other selectors instead of id based selection. The number of options in a drop down (combo box/list box) can be achieved using the following javascript code snippet,

document.getElementById('SELECT_ID').options.length;

using jquery we can achieve the same as,

$("#SELECT_ID").attr('options').length;

For eg:- if the html code for the select is like this

<select id="myselect">
<option value="I want sleep" >I want sleep</option>
<option value="I want go" >I want go</option>
<option value="I can drive" >I can drive</option>
<option value="I can code" >I can code</option>
</select>

then the javascript code will be,

document.getElementById('myselect').options.length;

using jquery we can achieve the same as,

$("#myselect").attr('options').length;

No comments:

Post a Comment