Moving Items from One Multi Select List To Another using jQuery

Dec 10, 2015 at 7:32 AM
s5-selectmoveitems

Although this may initially look like a complex problem to achieve, the solution is relatively simple, thanks to the useful jQuery methods and selectors. First download the latest jQuery file in a folder called scripts and add a reference to the jQuery file in your HTML page:
<script src="../scripts/jquery-1.11.1.min.js"></script>

Let’s look at the code now:
_$(function () { function moveItems(origin, dest) {
    $(origin).find(':selected').appendTo(dest);
}
 
function moveAllItems(origin, dest) {
    $(origin).children().appendTo(dest);
}
 
$('#left').click(function () {
    moveItems('#sbTwo', '#sbOne');
});
 
$('#right').on('click', function () {
    moveItems('#sbOne', '#sbTwo');
});
 
$('#leftall').on('click', function () {
    moveAllItems('#sbTwo', '#sbOne');
});
 
$('#rightall').on('click', function () {
    moveAllItems('#sbOne', '#sbTwo');
});
});

We’ve defined a moveItems() function that accepts two selector strings: origin select element and a destination select element. The selector string is converted into a jQuery object using $(origin) so that we can call some jQuery methods and selectors on it. The currently selected items are grabbed using the find() method with the :selected filter. Then the selected items are moved to the destination list with appendTo(). The appendTo() method accepts a target element, which in our case is a destination select box and appends the selected element to the end of the target element.

The moveAllItems() function works in a similar manner, except that in this case, instead of using the :selected filter to access the currently selected items, we are using children() to grab all the child elements in the origin list and appending to the bottom of the destination list.

And once this functionality has been defined, we just have to call the appropriate function from the respective click handler.
$('#left').click(function () {
    moveItems('#sbTwo', '#sbOne');
});
 
$('#right').on('click', function () {
    moveItems('#sbOne', '#sbTwo');
});
 
$('#leftall').on('click', function () {
    moveAllItems('#sbTwo', '#sbOne');
});
 
$('#rightall').on('click', function () {
    moveAllItems('#sbOne', '#sbTwo');
});
_
Save and run the example and you can transfer items between the two lists. For example, we have selected Gamma, Delta and Epsilon in the first list and used the ‘>’ click to move it to the second list. i have implemented the same while working on a uk based project for fixithere.