Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1504 How can I dynamically add/delete options from a select object using JavaScript?

You are here: irt.org | FAQ | JavaScript | Form | Q1504 [ previous next ]

Here is the code to do that. Enjoy!

<html>
 <head>
  <script type="text/javascript">
   function OnTransferBtnClick(blnFromLeft)
   {
    var LeftListBox = document.forms[0].lstLeft;
    var RightListBox = document.forms[0].lstRight;
    var ListItems = new Array();
    FromList = (blnFromLeft ? LeftListBox : RightListBox);
    ToList = (blnFromLeft ? RightListBox : LeftListBox);
    for(var i=(FromList.options.length - 1);i>=0;i--)
     if(FromList.options[i].selected)
       {
        ListItems[ListItems.length] = new Option(FromList.options[i].text);
        FromList.options[i] = null;
       }
     for(var i=ListItems.length - 1;i>=0;i--)
      ToList.options[ToList.options.length] = ListItems[i];
    }

   function OnBtnSubmitClick()
   {
    ListBox = document.forms[0].lstRight;
    if(ListBox.options.length==0)
      alert("You did not selection any item/items. Please choose an item/items from the left list box and transfer them to the right list box");
    else
    {
      var strChosenItems = "";
      for(var i=0;i<ListBox.options.length;i++)
        strChosenItems = strChosenItems + "  " + ListBox.options[i].text;
      alert("You chose : " + strChosenItems);
    }

   }
  </script>
 </head>

 <body bgColor="#FFFFF0">

 <form Name="SomeForm" method="POST">
  <table>
   <tr>
    <td>
     <select name="lstLeft" MULTIPLE size="5">
      <Option>Item1</Option>
      <Option>Item2</Option>
      <Option>Item3</Option>
      <Option>Item4</Option>
      <Option>Item5</Option>
      <Option>Item6</Option>
      <Option>Item7</Option>
      <Option>Item8</Option>
      <Option>Item9</Option>
      <Option>Item10</Option>
      <Option>Item11</Option>
      <Option>Item12</Option>
     </select>
    </td>
    <td>
     &nbsp
    </td>
    <td>
     <table>
      <tr>
       <td>
        <input Type="Button" Name="btnLtoR" Value=">>" onclick="OnTransferBtnClick(true)" title="Transfer Items Selected in the Left List Box to the Right List Box">
       </td>
      </tr>
      <tr>
       <td>
        <input Type="Button" Name="btnRtoL" Value="<<" onclick="OnTransferBtnClick(false)" title="Transfer Items Selected in the Right List Box to the Left List Box">
       </td>
      </tr>
     </table>
    </td>
    <td>
     &nbsp
    </td>
    <td>
     <select name="lstRight" MULTIPLE size="5">
     </select>
    </td>
   </tr>
   <tr>
    <td>
    <input Type="Submit" Name="btnSubmit" Value="OK" onClick="OnBtnSubmitClick()" Title="Submit this form">
    </td>
   </tr>
  </table>
 </form>

 </body>
 </html>

Submitted by Schahid Banday

Feedback on 'Q1504 How can I dynamically add/delete options from a select object using JavaScript?'

©2018 Martin Webb