js对ListBox 全选、反全选、删除选中项、上移、下移

<html>
  <head>
    <script type="text/javascript">
      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);
                    }
             }
          }
      }
      function listboxSelectDeselect(listID, isSelect) {
        var listbox = document.getElementById(listID);
        for(var count=0; count < listbox.options.length; count++) {
                listbox.options[count].selected = isSelect;
        }
    }

      function listboxMove(listID, direction) {
        var listbox = document.getElementById(listID);
        var selIndex = listbox.selectedIndex;
        if(-1 == selIndex) {
            alert("Please select an option to move.");
            return;
        }
        var increment = -1;
        if(direction == 'up')
            increment = -1;
        else
            increment = 1;

        if((selIndex + increment) < 0 ||
            (selIndex + increment) > (listbox.options.length-1)) {
            return;
        }

        var selValue = listbox.options[selIndex].value;
        var selText = listbox.options[selIndex].text;
        listbox.options[selIndex].value = listbox.options[selIndex + increment].value
        listbox.options[selIndex].text = listbox.options[selIndex + increment].text

        listbox.options[selIndex + increment].value = selValue;
        listbox.options[selIndex + increment].text = selText;

        listbox.selectedIndex = selIndex + increment;
    }
    </script>
  </head>
 
  <body>
    Click on below button. Now change some values in form and click the button again. <br>
    <select id="lsbox" name="lsbox" size="10" multiple="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>
    <button onclick="listboxSelectDeselect('lsbox', true);">Select All</button>
    <button onclick="listboxSelectDeselect('lsbox', false);">Deselect All</button>
    <button onclick="listboxMove('lsbox', 'up');">Move Up</button>
    <button onclick="listboxMove('lsbox', 'down');">Move Down</button>
  </body>
</html>

你可能感兴趣的:(listbox)