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.
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.
3. Now if something is selected then add the selected options to other list and also remove it from the selected list box.
So complete jQuery code for both the buttons is,
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.
1 | //Code Starts |
2 | var selectedOpts = $( '#lstBox1 option:selected' ); |
3 | //Code Ends |
1 | //Code Starts |
2 | if (selectedOpts.length == 0) { |
3 | alert( "Nothing to move." ); |
4 | e.preventDefault(); |
5 | } |
6 | //Code Ends |
1 | //Code Starts |
2 | $( '#lstBox2' ).append($(selectedOpts).clone()); |
3 | $(selectedOpts).remove(); |
4 | e.preventDefault(); |
5 | //Code Ends |
01 | //Code Starts |
02 | $(document).ready( function () { |
03 | $( '#btnRight' ).click( function (e) { |
04 | var selectedOpts = $( '#lstBox1 option:selected' ); |
05 | if (selectedOpts.length == 0) { |
06 | alert( "Nothing to move." ); |
07 | e.preventDefault(); |
08 | } |
09 |
10 | $( '#lstBox2' ).append($(selectedOpts).clone()); |
11 | $(selectedOpts).remove(); |
12 | e.preventDefault(); |
13 | }); |
14 |
15 | $( '#btnLeft' ).click( function (e) { |
16 | var selectedOpts = $( '#lstBox2 option:selected' ); |
17 | if (selectedOpts.length == 0) { |
18 | alert( "Nothing to move." ); |
19 | e.preventDefault(); |
20 | } |
21 |
22 | $( '#lstBox1' ).append($(selectedOpts).clone()); |
23 | $(selectedOpts).remove(); |
24 | e.preventDefault(); |
25 | }); |
26 | }); |
27 | //Code Ends |
No comments:
Post a Comment