文章源自:http://viralpatel.net/blogs/javascript-delete-multiple-values-options-listbox/
Deleting Multiple Values From Listbox in JavaScript
There was a requirement of deleting multiple options from a listbox using JavaScript. User can select multiple items from a Listbox. Once the delete button is pressed, remove all the values that are selected from the combobox.
Now the most intuitive solution for this problem would be to iterate through each option from the listbox and delete it if it is selected. So one would write following piece of HTML & JavaScript.
The HTML
Define a simple listbox with id lsbox and two buttons, Delete & Reset.
<table>
<tr>
<td align="center">
<select id="lsbox" name="lsbox" size="10" multiple>
<option value="1">India</option>
<option value="2">United States</option>
<option value="3">China</option>
<option value="4">Italy</option>
<option value="5">Germany</option>
<option value="6">Canada</option>
<option value="7">France</option>
<option value="8">United Kingdom</option>
</select>
</td>
</tr>
<tr>
<td align="center">
<button οnclick="listbox_remove('lsbox');">Delete</button>
<button οnclick="window.location.reload();">Reset</button>
</td>
</tr>
</table>
Below is the JavaScript code.
The (Incorrect) JavaScript
function listbox_remove(sourceID) { //get the listbox object from id. var src = document.getElementById(sourceID); //iterate through each option of the listbox for(var count = 0; count < src.options.length; count--) { //if the option is selected, delete the option if(src.options[count].selected == true) { try { src.remove(count, null); } catch(error) { src.remove(count); } } } }
That’s it right? Wait, this wont work correctly. Each time you delete an option using src.remove()
method, the remaining option’s index will decrease by 1. So if you have selected multiple values to delete, this wont behave as you expected.
The Correct JavaScript
Notice the loop highlighted line. We are iterating in opposite direction.
function listbox_remove(sourceID) { //get the listbox object from id. var src = document.getElementById(sourceID); //iterate through each option of the listbox for(var count= src.options.length-1; count >= 0; count--) { //if the option is selected, delete the option if(src.options[count].selected == true) { try { src.remove(count, null); } catch(error) { src.remove(count); } } } }
Following is the demo with correct JavaScript.