Showing posts with label combo. Show all posts
Showing posts with label combo. Show all posts

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;

Saturday, December 4, 2010

Setting value of drop down dynamically using javascript or jquery

If you want dynamically select or set a select or drop down or list box input value, in such cases the javascript or jquery code can be used to do this. Just a single line of code can do this as shown below. You will need to specify the unique id of the input field. You can use other jquery selectors too to do this if you don't want use the id.

To set the value of a select (drop down or list box) using java script is like this,

document.getElementById('Drop_Down_ID').value='The Option to Set';

the same can be achieved using jquery using this,

$("#my_select").val("The Option to Set");

for e.g:- if our html is like this,

<select id="my_select">
<option value="Want start a business">Want start a business</option>
<option value="Want find a job">Want find a job</option>
<option value="Want marry">Want marry</option>
<option value="Want sleep">Want sleep</option>
</select>

then we can use the javascript code as,

document.getElementById('my_select').value='Want marry';

to set the same option using jquery is,

$("#my_select").val("Want marry");