Loading ...

jQuery: Move items from one listbox to other | CodeAsp.Net

jQuery: Move items from one listbox to other

 /5
0 (0votes)

A person asked me on the forums on how to move items from one ListBox to other with jQuery. In this blog I will show the same with the solution which I gave to him. I am going to have four additional input buttons with two ListBoxes. The four buttons will serve the following purpose:

  • Add
  • Add All
  • Remove
  • Remove All

 Below is the complete sample code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(function () {
            var listBox1 = $('#<%= ListBox1.ClientID %>');
            var listBox2 = $('#<%= ListBox2.ClientID %>');
            $("#btnAdd").click(function () {
                listBox1.find('option:selected').appendTo(listBox2);
            });
            $("#btnAddAll").click(function () {
                listBox1.find('option').appendTo(listBox2);
            });
            $("#btnRemove").click(function () {
                listBox2.find('option:selected').appendTo(listBox1);
            });
            $("#btnRemoveAll").click(function () {
                listBox2.find('option').appendTo(listBox1);
            });


        });  
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
        <asp:ListItem Text="Text1" Value="1" ></asp:ListItem>
        <asp:ListItem Text="Text2" Value="2"></asp:ListItem>
        <asp:ListItem Text="Text3" Value="3"></asp:ListItem>
        <asp:ListItem Text="Text4" Value="4"></asp:ListItem>
    </asp:ListBox>

    <input id="btnAdd" type="button" value="Add" />
    <input id="btnAddAll" type="button" value="Add All" />
    <input id="btnRemove" type="button" value="Remove" />
    <input id="btnRemoveAll" type="button" value="Remove All" />

    <asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple"></asp:ListBox>
    </form>
</body>
</html>

                                                             

Do let me now your feedback, comments.

Comments (2)

   
user959655
This is client side script. What should we do after this if we want update the list box2 items in the database? We will get the no of items count as "0" because code behind does not know about this client side script, in this case we should write server side script only to move items from one box to another or is there any other way to do that?
1/31/2011
 · 
by
   
raghav_khunger
You can serialize the listbox values into a input hidden field and then you can grab the value of hidden field in server side.
1/31/2011
 · 
by

Top Posts