Pregunta

I want to swap elements from two different lists. So if I select something on the left list and on the right list they need to swap.

It currently looks like this: Html:

<ul id="sortable1" class="connectedSortable">
    <li value="1" class="ui-state-default">Sort1 Item 1</li>
    <li value="2" class="ui-state-default">Sort1 Item 2</li>
    <li value="3" class="ui-state-default">Sort1 Item 3</li>
    <li value="4" class="ui-state-default">Sort1 Item 4</li>
    <li value="5" class="ui-state-default">Sort1 Item 5</li>
</ul>

<ul id="sortable2" class="connectedSortable">
    <li value="1" class="ui-state-highlight">Sort2 Item 1</li>
    <li value="2" class="ui-state-highlight">Sort2 Item 2</li>
    <li value="3" class="ui-state-highlight">Sort2 Item 3</li>
    <li value="4" class="ui-state-highlight">Sort2 Item 4</li>
    <li value="5" class="ui-state-highlight">Sort2 Item 5</li>
</ul>

Jquery:

var testClickSort1 ='';
var testClickSort2 ='';

$(function() {
    $("#sortable1").sortable({
        cursor: 'pointer',
        connectWith: ".connectedSortable"
    }).disableSelection();

$("#sortable2").sortable({
    cursor: 'pointer',
    connectWith: ".connectedSortable"
}).disableSelection();

$("#sortable1 li").on('click',function(){
       // $("#testClickSort1").html($(this).attr('value'));
        testClickSort1 = $(this).attr('value'); 
        test();
});

$("#sortable2 li").on('click',function(){
       // $("#testClickSort2").html($(this).attr('value'));
        testClickSort2 = $(this).attr('value');
        test();
});
});

 function test(){ 
      if ((testClickSort1 != "") && (testClickSort2 != "")) {
         alert ("test: " + testClickSort1 + '' +  testClickSort2);
         //function to swap testclicksort1 with testclicksort2
         testClickSort1 = '';
         testClickSort2 = '';
}   
}

It can be viewed here:

http://jsfiddle.net/qkCcS/26/

Now I need to know what the function is to swap testclicksort1 with testclicksort2.

Thanks in advance.

Greets,

Wouter

¿Fue útil?

Solución

Can do something like this:

$(".connectedSortable").on('click','li', function () {
        /* make sure only one selected at a  time in a list*/
        $(this).siblings().removeClass('selected')
        $(this).toggleClass('selected');
        switchSelectedItems()
 }); 

function switchSelectedItems() {
    var $selected = $('.selected');
    /* make sure there is a pair*/
    if ($selected.length == 2) {
        $selected.each(function () {
            $(this).after($selected.not(this).clone().removeClass('selected'));
        }).remove()
    }
}

What this code does is make a clone of each of the selected items, places that after it's match in other list, then removes the originals

DEMO

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top