2010年6月24日 星期四

新增/移除select內的option

在這邊記錄一下 Javascript 如何新增 / 移除 select 內的 option
<input type="text" id="myText">
<input type="button" value="Add text to select"
      onclick="AddText()">
<br>
<select id="mySelect"></select>
<br>
<input type="button" value="Remove text from select"
      onclick="RemoveOption()">

<script language="javascript">
   function AddText()
   {
      var myText = document.getElementById("myText");
      var mySelect = document.getElementById("mySelect");
      var NewOption = document.createElement("option");
      NewOption.text = myText.value;
      NewOption.value = myText.value;
      try {
         mySelect.add(NewOption,null); //其他瀏覽器
      }
      catch (ex) {
         mySelect.add(NewOption); //IE
      }
   }

   function RemoveOption()
   {
      var mySelect = document.getElementById("mySelect");
      for (i=mySelect.options.length-1; i>=0; i--)
      {   //倒過來移除 options
         if (mySelect.options[i].selected)
            mySelect.remove(i);
      }
   }
</script>

兩個複選下拉選單互相搬移 option 的 Sample
<table border="0">
   <tr>
      <td>
         <select id="LeftPool" multiple size="5">
            <option value="1">Line 1</option>
            <option value="2">Line 2</option>
            <option value="3">Line 3</option>
         </select>
      </td>
      <td align="center">
         <input type="button" value=" → "
            onclick="MoveOption('LeftPool', 'RightPool')">
         <br><br>
         <input type="button" value=" ← "
            onclick="MoveOption('RightPool', 'LeftPool')">
      </td>
      <td>
         <select id="RightPool" multiple size="5">
         </select>
      </td>
   </tr>
</table>

<script language="javascript">
   function MoveOption(FromPool, ToPool)
   {
      var FromPool = document.getElementById(FromPool);
      var ToPool = document.getElementById(ToPool);
      for (i=0; i<FromPool.options.length; i++)
      {
         if (FromPool.options[i].selected)
         {
            var NewOption = document.createElement("option");
            NewOption.text = FromPool.options[i].text;
            NewOption.value = FromPool.options[i].value;
            try {
               ToPool.add(NewOption,null);
            }
            catch (ex) {
               ToPool.add(NewOption);
            }
         }
      }
      for (i=FromPool.options.length-1; i>=0; i--)
      {
         if (FromPool.options[i].selected)
            FromPool.remove(i);
      }
   }
</script>

沒有留言:

張貼留言