Move Items Between 2 ListBoxes

Just wrote this little JavaScript snippet by request of a coworker in this rainy and moody morning:

<script>
    function MoveItem(ctrlSource, ctrlTarget) {
        var Source = document.getElementById(ctrlSource);
        var Target = document.getElementById(ctrlTarget);

        if ((Source != null) && (Target != null)) {
            while ( Source.options.selectedIndex >= 0 ) {
                var newOption = new Option(); // Create a new instance of ListItem
                newOption.text = Source.options[Source.options.selectedIndex].text;
                newOption.value = Source.options[Source.options.selectedIndex].value;
               
                Target.options[Target.length] = newOption; //Append the item in Target
                Source.remove(Source.options.selectedIndex);  //Remove the item from Source
            }
        }
    }
</script>

HTML Code:

<table height="150" width="300">              
    <tr>
        <td>
            <asp:ListBox id="ListBox1" runat="server" Height="111px" SelectionMode="Multiple">
                <asp:ListItem Value="1">One</asp:ListItem>
                <asp:ListItem Value="2">Two</asp:ListItem>
                <asp:ListItem Value="3">Three</asp:ListItem>
            </asp:ListBox>
        </td>
        <td>
            <p>
                <input onclick="Javascript:MoveItem('ListBox1', 'ListBox2');" type="button" value="->" />
            </p>
            <p>
                <input onclick="Javascript:MoveItem('ListBox2', 'ListBox1');" type="button" value="<-" />
            </p>
        </td>
        <td>
            <asp:ListBox id="ListBox2" runat="server" Height="111px" SelectionMode="Multiple">
                <asp:ListItem Value="8">Eight</asp:ListItem>
                <asp:ListItem Value="9">Nine</asp:ListItem>
                <asp:ListItem Value="10">Ten</asp:ListItem>
            </asp:ListBox>
        </td>
    </tr>                 
</table>

Colt Kwong

45 Comments

Comments have been disabled for this content.