Friday, June 14, 2013

Move Selected list box items into the New list box using Javascript


In this post, I’m going to explain how to add the selected list box items into the new list box, both are asp.net controls. Include a new web form,  and add the below code in your web form. Hit F5 and you can see the output.

 
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Test.aspx.vb" Inherits="Blogging.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Styles/Site.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        function Move() {
            var oSrc = document.getElementById('<%= lstSource.ClientID %>');
            var oDest = document.getElementById('<%= lstDestination.ClientID %>');
            for (var i = 0; i < oSrc.options.length; i++) {
                if (oSrc.options[i].selected == true) {
                    var NewOption = new Option();
                    var selected = oSrc.options[i].value;
                    NewOption.text = oSrc.options[oSrc.options.selectedIndex].text;
                    NewOption.value = oSrc.options[oSrc.options.selectedIndex].value;
                    oDest.options[oDest.length] = NewOption;
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td class="style1">
                <asp:ListBox ID="lstSource" runat="server" SelectionMode="Single" Height="150px"
                    Width="250px">
                    <asp:ListItem Text="One" Value="1"></asp:ListItem>
                    <asp:ListItem Text="Two" Value="2"></asp:ListItem>
                </asp:ListBox>
            </td>
            <td class="style4">
                <input type="button" id="Add" value="Add" onclick="Move()" />
            </td>
            <td class="style1">
                <asp:ListBox ID="lstDestination" runat="server" SelectionMode="Single" Height="150px"
                    Width="250px" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Take a close look at the Java script function,"Move", which used to perform the required operation.

Output:


No comments:

Post a Comment

Please give your valuable comments to improve the contents