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.
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.
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.
JavaScript Array sort() The sort() sorts the elements as strings in alphabetical and ascending order.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With