如果用户在listbox列表框中选择了多个元素可以通过此JS代码一次性全部删除,非常有用。
function selectBoxRemove(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 http://www.75271.com if(src.options[count].selected == true) { try { src.remove(count, null); } catch(error) { src.remove(count); } } } }
详细范例,请看下面的代码
Click on below button. Now change some values in form and click the button again. <br> <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> <br> <button onclick="selectBoxRemove('lsbox');">Delete Selected Options</button> <script> function selectBoxRemove(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); } } } } </script>