function removeAllOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
selectbox.remove(i);
}
}
The for loop will remove all the elements with the value of i changing from last element of the array to first element of the array. function removeOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
if(selectbox.options[i].selected)
selectbox.remove(i);
}
}
Adding the options
There is a full tutorial on adding the options to list box. So here is the function.
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
function addOption_list(selectbox){
addOption(document.drop_list.SubCat, "One","One");
addOption(document.drop_list.SubCat, "Two","Two");
addOption(document.drop_list.SubCat, "Three","Three");
addOption(document.drop_list.SubCat, "Four","Four");
addOption(document.drop_list.SubCat, "Five","Five");
addOption(document.drop_list.SubCat, "Six","Six");
}
Now we will see how the select box with the form and buttons are placed in the body are of the page. Each button is connected to one function with on click event handler. See here <FORM name="drop_list" action="yourpage.php" method="POST" >
<SELECT id="SubCat" NAME="SubCat" MULTIPLE size=6 >
</SELECT><br>
<input type=button onClick="removeOptions(SubCat)"; value='Remove Selected'>
<input type=button onClick="removeAllOptions(SubCat)"; value='Remove All'>
<input type=button onClick="addOption_list()"; value='Add All'>
</form>
ashutosh | 02-03-2010 |
Thanks a lot. code is working fine in IE but not working with MOZILA. Please help me. |
smo | 02-03-2010 |
Check the demo link, it is working fine in FireFox, Chrome & IE |
Manas Sinha | 16-05-2010 |
Yes,It worked. Actually I used options.remove(i) so it was not removing all. Thanks... |
Lakshman | 28-06-2010 |
function removeAllOptions(selectbox) { selectbox.length = 0; } |
Achmend | 20-09-2010 |
I have many list boxes in one form. How do i clear all the list in all the boxes? |
suryaprakash | 21-01-2011 |
hi Achmend Get The All selectBox Ids in Javascript and and their Length ,then perForm Remove Method using For loop for all |
adi | 04-04-2011 |
i have a problem. i want to sign in using the username, password and one option from the drop down box, there are two option and on both optin different page is open how can i do this plz help me |
Srinivas | 26-03-2012 |
I dont need remove all ,remove and buttons there.As soon as i select an item from the list it should get deleted. |
05-01-2023 | |
Really helpful |