Introduction
This article explains how to easily add and remove multiple items from a ListBox in JavaScript as in the following:
Remove multiple items from the ListBox as in the following:
Step 1: For this, we will first use some controls like TextBox (txtValue) to add the value in the ListBox, ListBox (lstValue) and an Add and Delete Button as in the following:


- <input name="txtValue" type="text" />
- <input type="button" name="add" value="Add" onclick="addValue();" />
- <select name="lstValue" multiple>
- <option value="empty"></select>
- <input type="button" name="delete" value="Delete" onclick="deleteValue();" />
Step 2: Now we will write the code for adding the items in the ListBox like this:
- <script language="javascript" type="text/javascript">
- var i = 0;
- function addValue() {
- var v = document.form1.txtValue.value;
- // get the TextBox Value and assign it into the variable
- AddOpt = new Option(v, v);
- document.form1.lstValue.options[i++] = AddOpt;
- return true;
- }
- </script>
In this code
form1 is the name of the form and lstValue is the name of the ListBox and we will add the TextBox value in the form of the Option value (AddOpt) in the ListBox.
Step 3: Now we will write the code for deleting the value from the ListBox as in the following:
- document.form1.lstValue.options[i++] = AddOpt;

- function deleteValue() {
- var s = 1;
- var Index;
- if (document.form1.lstValue.selectedIndex == -1) {
- alert("Please select any item from the ListBox");
- return true;
- }
- while (s > 0) {
- Index = document.form1.lstValue.selectedIndex;
- if (Index >= 0) {
- document.form1.lstValue.options[Index] = null;
- --i;
- }
- else
- s = 0;
- }
- return true;
- }
In this Code
Here we assign the SelectedIndex Value of the ListBox in the variable Index like this:
- if (document.form1.lstValue.selectedIndex == -1) {
- alert("Please select any item from the ListBox");
- return true;
- }
- The following code will be used to determine whether there are any items in the LisBox:
- while (s > 0) {
- Index = document.form1.lstValue.selectedIndex;
- if (Index >= 0) {
- document.form1.lstValue.options[Index] = null;
- --i;
- }
- else
- s = 0;
- }
- Index = document.form1.lstValue.selectedIndex;





Gowtham RajamanickamPosted Mar 13, 2015, 2:15 AM
good one..
Gowtham RajamanickamPosted Mar 13, 2015, 2:15 AM
great and simple...