Search code examples
javascriptdrag-and-dropsortablejs

How to get the order of a sortable list made with sortablejs?


My code looks similar to this:

new Sortable(sortablelist, {
                    animation: 150,
                    ghostClass: 'sortable-ghost'
                });
.box {
        background-color: powderblue;
        margin: 4px;
        padding: 2px;
        width: 25%;
        cursor: move;
    }
<!DOCTYPE html>
<html>
    <head>
        <title>test</title>
    <script src="https://raw.githack.com/SortableJS/Sortable/master/Sortable.js"></script>
    </head>

    <body>
    <center>
  
        <div id="sortablelist">
            <div class="box" id="Item 1">Item 1</div>
            <div class="box" id="Item 2">Item 2</div>
            <div class="box" id="Item 3">Item 3</div>
        </div>
    
    </center>
    </body>
</html>

Im a beginner, hope you can help me. I feel like I already searched the hole web. The order will continue to be saved in a database, but I am now a little experienced with PHP and think I can manage this.


Solution

  • If you use JQuery you can use sortable.toArray().

    $("#sortablelist").sortable.toArray("orderedIds");
    

    This will put the IDs of all the items in the sortable into an array. So in your case it will return (if you haven't changed the order):

    ["Item 1", "Item 2", "Item 3"]