Move items from one Listbox to another using jQuery

ASP.NET UI

There are two Listboxes – list1 and list2. And four buttons. We want to move items from the one Listbox to another.

There is a:

  • Add button to add selected items.
  • Add All button to add all items.
  • Remove button to remove selected items.
  • Remove All button to remove all items.

We are using classic ASP.NET Web forms.

<div>
  <asp:ListBox ID="list1" runat="server">
    <asp:ListItem Text="One"></asp:ListItem>
    <asp:ListItem Text="Two"></asp:ListItem>
    <asp:ListItem Text="Three"></asp:ListItem>
  </asp:ListBox>
  <asp:Button ID="btnAdd" runat="server" Text=">" />
  <asp:Button ID="btnAddAll" runat="server" Text=">>" />
  <asp:Button ID="btnRemove" runat="server" Text="<"/>
  <asp:Button ID="btnRemoveAll" runat="server" Text="<<" />
  <asp:ListBox ID="list2" runat="server"></asp:ListBox>
</div>

jQuery

The jQuery code for moving items is simple enough.

$(document).ready(
    function () {
        $('#btnAdd').click(
            function (e) {
                $('#list1 > option:selected').appendTo('#list2');
                e.preventDefault();
            });

        $('#btnAddAll').click(
            function (e) {
                $('#list1 > option').appendTo('#list2');
                e.preventDefault();
            });

        $('#btnRemove').click(
            function (e) {
                $('#list2 > option:selected').appendTo('#list1');
                e.preventDefault();
            });

        $('#btnRemoveAll').click(
            function (e) {
                $('#list2 > option').appendTo('#list1');
                e.preventDefault();
            });
    });

We have click handlers for each of the button. The selector for the selected items in the first Listbox is list1 > option:selected'. appendTo function appends all the selected items to the other Listbox. For selecting all items, the selector is #list1 > option. Remove and Remove all does the reverse. Pick items from list2 and append it to list1.

Finally, we want to prevent event bubbling. This ensures that the page is not posted back. e.preventDefault function prevents event bubbling.

Update 1: A Part 2 of the article has been posted. Part 2 resolves issues with server-side postback.

Update 2: I moved to WordPress in 2016. And reset my stats. With my old blog, this article was the most popular.

Related Posts

Leave a Reply

Your email address will not be published.