Tuesday, June 14, 2011

work with select box in javascript

Here we going to see about how to work with select box in javascript. first we going to see how to check any options selected in select box. we can easily check using selectedIndex.

document.getElementById('id').selectedIndex;

it will return '-1' when no one selected otherwise give the index of selected option like 0,1,2 ...

find number of options in select  box:
--------------------------------------
 just check the length , it will return number of options

document.getElementById('id').option.length;

Add options to select box:
---------------------------
Adding options to select box via options.add() like below
options.text = 'test';
options.value = 'test_value';
document.getElementById('id').options.add(options);

Remove option from select box:
---------------------------------
similar to add option you can remove the options from select box using options.remove();
In remove option we need to pass the index value
document.getElementById('id').options.remove(0);
This will remove the first option in select box. we will remove all options using for loop or just set the options length as 0.

document.getElementById('id').option.length=0;

this will remove all the options in select box.


No comments:

Post a Comment