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

No comments:

Post a Comment