Monday, May 21, 2012

How to move items between ListBox using jQuery

In this post, I will show you how you can easily move items from one listbox to another listbox using jQuery. The beauty of this code is that you can also move multiple items together.


As you can see from above image that there should be 2 button to move items from one list to another. So code will be identical for both the buttons, only the listbox's id gets changed.

1. First get the list box selected options.
//Code Starts
var selectedOpts = $('#lstBox1 option:selected');
//Code Ends
2. It is quite possible that nothing is selected and button is clicked. So it is important to check if anything is selected or not. If not then alert the user.
//Code Starts
if (selectedOpts.length == 0) {
   alert("Nothing to move.");
   e.preventDefault();
}
//Code Ends
3. Now if something is selected then add the selected options to other list and also remove it from the selected list box.
//Code Starts
$('#lstBox2').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
//Code Ends
So complete jQuery code for both the buttons is,
//Code Starts
$(document).ready(function() {
    $('#btnRight').click(function(e) {
        var selectedOpts = $('#lstBox1 option:selected');
        if (selectedOpts.length == 0) {
            alert("Nothing to move.");
            e.preventDefault();
        }

        $('#lstBox2').append($(selectedOpts).clone());
        $(selectedOpts).remove();
        e.preventDefault();
    });

    $('#btnLeft').click(function(e) {
        var selectedOpts = $('#lstBox2 option:selected');
        if (selectedOpts.length == 0) {
            alert("Nothing to move.");
            e.preventDefault();
        }

        $('#lstBox1').append($(selectedOpts).clone());
        $(selectedOpts).remove();
        e.preventDefault();
    });
});​
//Code Ends
See result below.



Feel free to contact me for any help related to jQuery, I will gladly help you.