要从列表框同时删除多个项目,我们不能从上到下的删除,因为上面的项目每删除一个,下面的项目的索引号就会变化,所以只能从下向上删除,这样就不会出现索引号乱变的问题了。
html代码
<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 onclick="listbox_remove('lsbox');">Delete</button> <button onclick="window.location.reload();">Reset</button> </td> </tr> </table>
javascript代码如下:
function listbox_remove(sourceID) { // from http://www.75271.com //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); } } } }
当然,如果使用jQuery来删除,那就方便了,一句话就搞定了
$("#sourceId").find('option:selected').remove();