Java Script to Dynamically Add, Remove, and Change Items in a Select List
By Stephen Bucaro
Add Items to a Select List
You can dynamically add items to a select list
When you click on the [Add Cheese] button, Cheese will be added to the list.
You add as much cheese as you like. Example code for a adding an item to a
select list is shown below.
<script type="text/javascript">
function addItem(list)
{
var newItem = document.createElement("option");
newItem.value = "Cheese";
newItem.text = "Cheese";
list.add(newItem);
}
</script>
<form name="myForm">
<select name="mySelect" size="8">
<option value="Bread">Bread</option>
<option value="Coffee">Coffee</option>
<option value="Fruit">Fruit</option>
<option value="Pie">Pie</option>
<option value="Salad">Salad</option>
<option value="Soup">Soup</option>
<option value="Wine">Wine</option>
</select>
<br /><input type="button" value="Add Cheese" onclick="addItem(this.form.mySelect)">
</form>
In this code, the onclick event of the [Add Cheese] button calls a function
named addItem passing the select list as a parameter. The addItem function
uses the select list's add method to add "Cheese".
Remove Items from a Select List
You can dynamically remove items from a select list.
When you click on the [Remove Item] button, the selected item will be removed
from the list. You can remove all the items from the list if you like. Example
code for removing an item from a select list is shown below.
<script type="text/javascript">
function removeItem(list)
{
list.remove(list.selectedIndex)
}
</script>
<form name="myForm">
<select name="mySelect" size="7">
<option value="Bread">Bread</option>
<option value="Coffee">Coffee</option>
<option value="Fruit">Fruit</option>
<option selected value="Pie">Pie</option>
<option value="Salad">Salad</option>
<option value="Soup">Soup</option>
<option value="Wine">Wine</option>
</select>
<br /><input type="button" value="Remove Item" onclick="removeItem(this.form.mySelect)">
</form>
In this code, the onclick event of the [Remove Item] button calls a function
named removeItem passing the select list as a parameter. The removeItem
function uses the select list's remove method to remove the selected item.
|