How JavaScript removes multiple items from the listbox simultaneously _javascript tips

Source: Internet
Author: User
To delete multiple items from the list box at the same time, we cannot delete from top to bottom, because the item above is deleted, the index number of the item below will change, so you can only remove it from the bottom, so there is no problem with the index number being messed up.

HTML code
Copy Code code as follows:

<table>
<tr>
<TD align= "center" >
<select id= "Lsbox" name= "Lsbox" size= "ten" 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 onclick= "Listbox_remove (' Lsbox ');" >Delete</button>
<button onclick= "Window.location.reload ();" >Reset</button>
</td>
</tr>
</table>

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

Src.remove (count);
}
}
}
}

Of course, if you use jquery to delete, that's convenient, a word is done
Copy Code code as follows:

$ ("#sourceId"). Find (' option:selected '). Remove ();
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.