Swapping of ListBox Items using jQuery

The interchanging of Items of one list-box to other list-box is done in this Swapping of List-box Items.Here the swapping is done in the Client Side using jQuery.For Swapping the Items  I took  two Array lists .

Initially I have filled the two array lists with the list boxes data.Now I have written a Common Method to swap the Items from one list box to other.

HTML Markup:


<div>
        <asp:ListBox runat="server" ID="lstbx1">
            <asp:ListItem Text="text1" />
            <asp:ListItem Text="text2" />
            <asp:ListItem Text="text3" />
            <asp:ListItem Text="text4" />
        </asp:ListBox>
        <br />
        <asp:ListBox runat="server" ID="lstbx2">
            <asp:ListItem Text="text5" />
            <asp:ListItem Text="text6" />
            <asp:ListItem Text="text7" />
            <asp:ListItem Text="text8" />
        </asp:ListBox>
        <asp:Button Text="Swap Items " ID="btnSwap" runat="server" 
            onclick="btnSwap_Click" />
    </div>

In the button click I have Swapping of Items in the button click.The jQuery Code is given below

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('input[id$=btnSwap]').click(function () {
                var listbox1 = new Array();
                var listbox2 = new Array();
                for (var i = 0; i < $('select[id$=lstbx1]')[0].length; i++) {
                    listbox1.push($('select[id$=lstbx1]')[0][i].text);
                }
                for (var i = 0; i < $('select[id$=lstbx2]')[0].length; i++) {
                    listbox2.push($('select[id$=lstbx2]')[0][i].text);
                }
                $('select[id$=lstbx1]').empty(); $('select[id$=lstbx2]').empty();
                SwapListBoxItems(listbox2, $('select[id$=lstbx1]')[0].id);
                SwapListBoxItems(listbox1, $('select[id$=lstbx2]')[0].id);
                alert('Swapping done !');
                return 4 == 2;
            });
        });

        function SwapListBoxItems(lstbx, lstbxID) {
            for (var j = 0; j < lstbx.length; j++) {
                $("select[id$=" + lstbxID + "]").append("<option>" + lstbx[j] + "</option>");
            }
        }

    </script>

Now the items in the first  listbox will be swapped to the Second listbox and vice versa.This is how we can swap the items using Client Side Scripting .

Below is the output of the above executed code
Swapping of Listbox Items

Popular posts from this blog

Exporting to excel from a custom class object using C#.NET

Get the Clicked Cell Value and Column Name of GridView in ASP.NET

How to apply watermark to the textbox and dropdownlist?