Move items from one listbox to another using jQuery
I have two listboxes - list1, list2. There are four buttons. Add button to move selected items from one listbox to another. AddAll button to move all items from one listbox to another. Remove and RemoveAll buttons do the reverse operation. The code below shows how this can be done using jQuery.
HTML
<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>
Javascript
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script type="text/javascript"> $(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(); }); }); </script>
The selector for selecting items in a listbox is $('list1 > option:selected'). AppendTo function moves item from one element to another. e.preventDefault prevents event bubbling so that the page is not posted back.
Category : Javascript
@Manivannan, I want to investigate this a little bit more. There is also another requirement where moving a item from one listbox to another should not affect the sort order.
I intended this post to be a simple post which shows what can be done using jQuery. Since, there is some interest in this post, I will spend my time and make it better.
Hi Vijay..
In the code behind,Wen v trying to access the listbox item countin the target source.. it still showing zero..?? Do u hav any idea abt this issue..??
Really nice code...
There is no sort function readily available for listbox. One way to do this is to use the each() function for the listbox items. I will try to come up with another post on this when I find a neat solution.
Your code is good.. I love it. Anyway can you help me with this. Can we sort the listbox after moving it..