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]);
});
});
This will work without the sortable() method, it seems to interfere with the selectable() method.
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.
jsFiddle