Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rubaxa Sortable how to get array of items

I know this is going to be obvious, but I can't figure it out.

Im using Rubaxa/sortable and would like to update my DB with ajax when an item is added, removed or list is sorted.

    var editableList = Sortable.create(document.getElementById('editable'), {
    animation: 150,
    filter: '.js-remove',
    onFilter: function (evt) {
        evt.item.parentNode.removeChild(evt.item);
    },
    onSort: function(evt) {
        console.log(editableList.toArray()); // not working

    }
});

document.getElementById('addUser').onclick = function () {
    Ply.dialog('prompt', {
        title: 'Add',
        form: { name: 'name' }
    }).done(function (ui) {
        var el = document.createElement('li');
        el.innerHTML = ui.data.name + '<i class="js-remove">✖</i>';
        editableList.el.appendChild(el);
    });
};

Any help is appreciated.

like image 226
Thom Avatar asked Apr 28 '16 18:04

Thom


People also ask

How does array sort work?

Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

How do I sort a string array in jQuery?

The jQuery array sort() function is used to sorts the elements of the array. This function is a built-in function in jQuery. This function sorts the array of a number, string, and object in ascending and descending order.

How do I sort in alphabetical order in JavaScript?

JavaScript Array sort() The sort() sorts the elements as strings in alphabetical and ascending order.

How do you sort names in JavaScript?

We can do this in JavaScript by using the sort() method directly or with the compare function. In case you are in a rush, here are the two ways: // order an array of names names. sort(); // order an array of objects with name users.


1 Answers

I solved it this way:

HTML:

<ul id="products">
    <li data-key="1"></li>
    <li data-key="2"></li>
    <li data-key="3"></li>
</ul>

JS:

var element = $('#products')[0];
var sortable = new Sortable(element, {
    handle: '.drag-handle',
    ghostClass: 'drag-ghost',
    onSort: function (e) {
        var items = e.to.children;
        var result = [];
        for (var i = 0; i < items.length; i++) {
            result.push($(items[i]).data('key'));
        }
        console.log(result);
        /* Do ajax call here */
    }
});

After sorting you will get the array of the items keys:

[2, 3, 1]
like image 169
leealex Avatar answered Oct 04 '22 11:10

leealex