Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI sortable’s serialize method excludes one item

I am using jQuery UI sortable for a list of elements on a page whose order I want to save in the database every time it’s changed.

However, I’m experiencing a weird bug (it seems to me like one): both the serialize and toArray methods always exclude one item from the produced serialised string (or array). That always is the item being currently dragged. Which means the order is never actually tracked properly.

Here’s an example of my javascript:

$('.setContent').sortable({change:

    function(event, ui) {

        // Serialise the new order
        var newOrder = $('.setContent').sortable('serialize');

        // Add the current set id and the action name
        newOrder += '&setId='+currentSet+'&action=usrStuff:changeCardsOrder';

        // Send the data to the server
        $.post('ajax.php', newOrder);

   }

});

And the HTML:

<div class="setContent>
    <div class="cardSmall" id="card_5">
        <div class="hanzi">俄国</div>
        <div class="meaning">Russia</div>
    </div>
    <div class="cardSmall" id="card_4">
        <div class="hanzi">韩国</div>
        <div class="meaning">Korea</div>
    </div>
    <div class="cardSmall" id="card_6">
        <div class="hanzi">中国</div>
        <div class="meaning">China</div>
    </div>
    <div class="cardSmall" id="card_12">
        <div class="hanzi">日本</div>
        <div class="meaning">Japan</div>
    </div>
    <div class="cardSmall" id="card_13">
        <div class="hanzi">德国</div>
        <div class="meaning">Germany</div>
    </div>
    <div class="cardSmall" id="card_17">
        <div class="hanzi">巴西</div>
        <div class="meaning">Brasil</div>
    </div>
    <div class="cardSmall" id="card_14">
        <div class="hanzi">法国</div>
        <div class="meaning">France</div>
    </div>
    <div class="cardSmall" id="card_19">
        <div class="hanzi">美国</div>
        <div class="meaning">America</div>
    </div>
    <div class="cardSmall" id="card_16">
        <div class="hanzi">英国</div>
        <div class="meaning">England</div>
    </div>
</div>

So, in this case, there are nine items in the list. But the sortable method will only return information about eight.

Screenshot of the window and with the JS console open

So how do I fix this?

like image 930
Arnold Avatar asked Feb 23 '23 06:02

Arnold


1 Answers

You probably want the update event, not the change event.

change fires during sorting whenever the ordering of the items in the DOM changes, even if the user hasn't let go of the item they're moving. update fires after the user has changed the order of the sortable elements.

like image 159
John Flatness Avatar answered Mar 03 '23 22:03

John Flatness