over around all the elements in listbox

Discussion in 'JavaScript' started by mystic-d, Aug 25, 2007.

  1. #1
    hey
    can someone plz tell me , how can i build a function on Javascript that copy one listbox to another listbox , i mean how can i take one element from the first lisbox and copy him to the another listbox for any iteration of the loop ?
    thanks !
     
    mystic-d, Aug 25, 2007 IP
  2. mjamesb

    mjamesb Member

    Messages:
    88
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    48
    #2
    This example takes all selected options from list1 and moves them to list2

    <body>
    <table>
    <tr>
    <td>
    <select style="width:100px;" name="List1" id="List1" size="4" multiple>
    <option value="Opt1">Opt1</option>
    <option value="Opt2">Opt2</option>
    <option value="Opt3">Opt3</option>
    <option value="Opt4">Opt4</option>
    </select>
    </td>
    <td><input type="button" onclick="MoveOpts()" value="Move Options"></td>
    <td>
    <select style="width:100px;" name="List2" id="List2" size="4"></select>
    </td>
    </tr>
    </table>

    <script language="javascript">
    function MoveOpts()
    {
    var list1 = document.getElementById("List1");
    var list2 = document.getElementById("List2");
    //start from bottom and work way up if removing from list 1..if not removing from list 1 order doesn't matter
    for (var i = list1.options.length-1; i>=0; i--)
    {
    //this will only take selected ones.
    if (list1.options.selected)
    {
    var myNewOption = new Option(list1.options.text, list1.options.value);
    list2.options[list2.options.length] = myNewOption;
    //if you want to remove from list 1
    list1.options = null;
    }
    }

    }
    </script>
    </body>
     
    mjamesb, Aug 26, 2007 IP