How can JavaScript delete multiple items from the listbox at the same time

  • 2020-03-26 21:25:32
  • OfStack

To delete multiple items from the list box at the same time, we cannot delete from the top to the bottom, because the above items are deleted each time, the index number of the following items will change, so we can only delete from the bottom up, so there will be no index number chaos problem.

The HTML code
<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> 
<td align="center"> 
<button onclick="listbox_remove('lsbox');">Delete</button> 
<button onclick="window.location.reload();">Reset</button> 

The javascript code is as follows:
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) { 


Of course, if you use jQuery to delete, that is convenient, a sentence is done

Related articles: