开发者

Sort LIs in different ULs with jQuery

I have this markup dinamically generated through PHP/MySQL

<div id="sortable">
    <h3>Italy</h3>
    <ul>
        <li id="row_1">Record > 1</li>
        <li id="row_2">Record > 2</li>
        <li id="row_3">Record > 3</li>
    </ul>

    <h3>Europe</h3>
    <ul>
        <li id="row_4">Record > 4</li>
        <li id="row_5">Record > 5</li>
        <li id="row_6">Record > 6</li>
    </ul>

    <h3>World</h3>
    <ul>
        <li id="row_7">Record > 7</li>
        <li id="row_9">Record > 9</li>
        <li id="row_8">Record > 8</li>
    </ul>
</div>
<div id="response"></div>

I can drag the LIs with jQuery UI sortable to new positions, and get their new order with "serialize", ready for database update As you can see开发者_如何学Go, there are 3 ULs, but their N LIs are all related so I get a N-items "serialization" with each drag, and that's exactly what I want

So, ie, if I move Record 3 in Record 1 place, I get this:

3,2,1,4,5,6,7,8,9 < this is just what I want

and not this:

3,2,1 < this is NOT what I want

This is my jQuery code:

$("#sortable").sortable({
    items: 'li',
    opacity: 0.6,
    cursor: 'move',
    update: function() {
    var order = $(this).sortable("serialize") + '&nAction=move';
    $.post("mypage.php", order, function(response){
        $("#response").html(response);
    });
}
}).disableSelection();

It's working, but not as I'd like: I mean that I need to drag/drop only LIs within their respective UL, and NOT from one UL to another (always retaining the N-items serialization)

In other words, I'd like to be able to sort records 1, 2 and 3 among them, 4, 5 and 6 among them and 7,8,9 among them, without mixing (i.e., record 1 can't go in group 4,5,6 nor in group 7,8,9)

Of course, always getting the N-items serialization! (and that's the main reason why I applied "sortable" to a container dive and then specified LI items)

I tried with "containment: 'parent'", but it works only for the first drag/drop

Here are two online examples made with jsFiddle:

  1. The original one, with LIs going from one UL to the other
  2. The version with "containment", that works only on the first drag but it's a mess in the following drags


http://jsfiddle.net/zAUT3/2/ - apply sortable to each individual ul separately. Then, whenever you need to serialize, just use each() to loop over all the sortables, and build up a composite serialization.


Here's the modified code from the jsFiddle linked above:

$(".sortable").sortable({
    items: 'li',
    opacity: 0.6,
    cursor: 'move',
    update: function() {
        var order ='';
        $('#allGroups .sortable').each(function(i,el) {
            order += $(el).sortable("serialize") +'&';
        });
        order += 'nAction=move';

        alert(order);
        $.post("/echo/html/", order, function(response) {
            $("#response").html(response);
        });
    }
}).disableSelection();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜