The following tutorial with code will guide you how to remove options/items to the list box dynamically using javascript
Removing All OptionsTo remove all the options from the list box we will loop through all the elements of the list box and remove one by one. We will use for loop to loop from 0 to selectbox.options.length-1. The total length ( or the number of elements ) of the array we can get by using selectbox.options.length and to this we are subtracting 1 as the first elements starts from 0 ( not from 1 ). Here is the function
function removeAllOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
selectbox.remove(i);
}
}
Removing Selected OptionsNow, If you want to remove the options selected in multiple select list box and then by pressing the button. Here also we will use the similar function like above but before deleting we will check if the option is checked or not. selectbox.options[i].selected will return true if the option is selected. This way we will check all the elements of the list box and if they are checked then we will add the command selectbox.options.remove(i); to remove that particular option from the list box. Here is the function
function removeOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
if(selectbox.options[i].selected)
selectbox.remove(i);
}
}
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.asp" method="POST" >
<SELECT id="SubCat" NAME="SubCat" MULTIPLE size=6 width=10>
<OPTION value="1">One</OPTION>
<OPTION value="2">Two</OPTION>
<OPTION value="3">Three</OPTION>
</SELECT><br>
<input type=button onClick="removeOptions(SubCat)"; value='Remove Selected'>
<input type=button onClick="removeAllOptions(SubCat)"; value='Remove All'>
</form>