0

i have seen a question already asked and answered about swapping the values/items between two drop-down lists, How to swap values in select lists with jquery?

My question is can it be done between to jquery ui-selectable lists. where you click one element in list 1 and another in list 2 and clicking a swap button would transfer the contents of each item/div that was selected from one to the other?

HTML:

<button>Swap Values</button>
<div style="display:inline-block">
<div id="selectable" class="mySel">
    <div value=Item1>Item1</div>
    <div value=Item2>Item2</div>
    <div value=Item3>Item3</div>
    <div value=Item4>Item4</div>
</div>

<div id="selectable2" class="mySel2">
    <div value=Item1>Item1</div>
    <div value=Item2>Item2</div>
    <div value=Item3>Item3</div>
    <div value=Item4>Item4</div>
    <div value=Item1>Item5</div>
    <div value=Item2>Item6</div>
    <div value=Item3>Item7</div>
    <div value=Item4>Item8</div>
</div>
</div>

CSS:

*{padding:6px; font-size:1.1em}

.mySel, .mySel2{
height: 300px;
width: 200px;
overflow: auto;
border: solid 2px black;
margin-bottom: 20px;
float:left;
margin:10px;
}

.mySel > DIV, .mySel2 > DIV{
height: 50px;
border: solid 1px red;
}

#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
#selectable2 .ui-selecting { background: #FECA40; }
#selectable2 .ui-selected { background: #F39814; color: white; }

JQUERY selectable:

$("#selectable, #selectable2").selectable();

JQUERY sortable:

$(".mySel, .mySel2").sortable({
    tolerance: 'pointer',
    connectWith: '.mySel, .mySel2',
    helper: 'original',
    scroll: true
});

JQUERY Swap values attempted code:

$('button').click(function() {
    var new1 = [];

    $('.mySel, .mySel2').each(function(i) {
        new1[i] = $(this).val();
    });
    new1.reverse();
    $('.mySel, .mySel2').each(function(i) {
        $(this).val(new1[i]);
    });
});
Community
  • 1
  • 1
user1648449
  • 97
  • 2
  • 10

1 Answers1

1

This will work without the sortable() method, it seems to interfere with the selectable() method.

$('button').click(function(){
   $('#selectable .ui-selected').removeClass('ui-selected').appendTo('#selectable2');
   $('#selectable2 .ui-selected').removeClass('ui-selected').appendTo('#selectable');
});

edit: It will work with the sortable method, as long as sortable() runs second. *edit: in response to followup questions*

Additional Questions

How to tell if an element with a value of "Item1" already exists in list2 before moving it over?

There were a few fun bit to work out here. The first is whether or not the identical term in the opposite list was being swapped or not. If it is, the swapping can continue because both lists will continue to only have one of each value. Second, if a duplicate is found, the script must not complete the swapping. Both sets of lists needed to be checked for duplicates before the swap could occur.

I fixed this with a combination of some complicated jQuery selectors and a separate evaluation function that would either return true or false, depending on whether or not there were duplicates. I've added comments to the code below explaining how it works.

function testFor($o, $p) { //two collections of Items we are comparing
        var retVal = true; //By default, this script returns true, a mismatched pair results in a return: false;
        $o.each(function() { //Look at each element in the first collection
            var thisDivValue = $(this).attr('value'); //Grab it's value=""
            if ($p.parent().find('div[value=' + thisDivValue + ']').not('.ui-selected').length > 0) { 
            //Search in the opposite collection for an item with a matching value that is NOT selected for swapping, if you find it, return false.
                retVal = false;
                return false;
            }
            else {return true;}
        });
        return retVal; //True or false depending on what was set above.
    }
function showError() {
    alert('DUPLICATE FOUND');
}
$("#selectable, #selectable2").selectable();
$(".mySel, .mySel2").sortable({
    tolerance: 'pointer',
    connectWith: '.mySel, .mySel2',
    helper: 'original',
    scroll: true
});
$('button').click(function() {
    var v = $('#selectable2>div');
    var w = $('#selectable>div');
    var x = $('#selectable .ui-selected');
    var y = $('#selectable2 .ui-selected');
    if ((w.length - x.length + y.length) > 4) {return false;}
    if ((v.length - y.length + x.length) > 8) {return false;}
    if (testFor(x, y) && testFor(y, x)) { //Both of these tests must return TRUE in order for the swap to happen
        $('#selectable .ui-selected').removeClass('ui-selected').appendTo('#selectable2');
        $('#selectable2 .ui-selected').removeClass('ui-selected').appendTo('#selectable');
    }
    else {showError();}
});​

jsFiddle

Chris Like
  • 280
  • 1
  • 8
  • Yeah that's what I'm looking for, thanks. Couple of questions though. 1) Is it possible to have each list with a maximum number of items allowed. List1 a max. of 4, list2 a max. of 8. That way each list must have an item selected to be swapped, whereas right now an item may be swapped by itself. 2)Can the left column (list1, #selectable) have a restriction that the same item cannot be together. Example, the left column cant have item1 and item1 together? – user1648449 Dec 10 '12 at 11:45
  • 1) You can use jQuery to create an array each of the child-divs of #selectable and #selectable2, and compare their length property against the length of each respective collection of `.ui-selected` divs. Example: `var w = $('#selectable>div').length;` `var x = $('#selectable .ui-selected').length;` `var y = $('#selectable2 .ui-selected').length;` and then use an `if` statement to calculate the total if a swap occurs: `if ((w - x + y) > 4) {error}`. – Chris Like Dec 10 '12 at 15:38
  • 2) You can use jQuery's .attr('value') method to compare the existing values in the left-hand column against the intended swap values in the right-hand column. If you find a match, display an error message. – Chris Like Dec 10 '12 at 15:42
  • Okay thanks for the help again. The first part (1) I figured out with your help. The second part (2) I have partially completed, but can't figure out how to call all the div values in list 1? I tried `var sel1 = $('#selectable > div').attr('value')` and also `.children()`, but it only seems to get the first value ie - value=Item1. Items 2, 3 and 4 can still be moved from list 2 to list 1? I also did `var sel2 = $(#selectable2 .ui-selected).attr('value')` and then a if statement between the two `==` as a reference. – user1648449 Dec 11 '12 at 03:08
  • I'm going to add another answer with more space for explaining below. – Chris Like Dec 11 '12 at 05:04
  • Also, the way around the variable only matching the first value is that `var sel1 = $('#selectable > div')` is a collection of elements. To get each one's value, you need to iterate through the collection using jQuery's .each() method. More information about .each() here: http://api.jquery.com/each/ – Chris Like Dec 11 '12 at 05:20
  • That's the operation i was looking for. Only i was trying to make the setup work for the left list ('.mysel') only. In other words, List1 (left (4)) cannot have item 2 and item 2 etc... List 2 (right (8)) may have item 2 and item 2 etc... Your code has the desired operation for list 1 (4 items), but it restricts list 2 (8 items) from having duplicate items. I want to allow duplicates to exist in List 2 (8 items). So what im trying do is - 1)check all four item values in list1. 2)select an item in list2. 3)if the selected item in list2 does not match any of the four values in list1 allow swap. – user1648449 Dec 11 '12 at 12:22
  • All you need to do is remove the second test that runs `testFor(y,x)`. It will then only require the left-section to be duplicate-free. – Chris Like Dec 12 '12 at 02:46