I'm trying to figure out how I can track how the elements in a jQuery sortable. Let's say that I have four elements (divs) in my sortable, each have an unique id. Let's call them #100, #200, #300 and #400 and they're presented in that order to start with. But when I move #100 to let's say spot number 3, I need to be able to save the new position for this id, but also make sure that the other ones get updated position values aswell.
Am I making any sense? Basically I want to get the positions of each unique id, so I can save the order of the list for later use.
I haven't been able to find something that reports for all the elements in a sortable, just for the one that was moved..
Point me in the right direction? Thanks
You can use the stop-event provided to you in sortable to keep track of the items. This is a small example;
(function($) {
$('#sortable').sortable({
stop: function(e, ui) {
console.log($.map($(this).find('li'), function(el) {
return el.id + ' = ' + $(el).index();
}));
}
});
})(jQuery);
This logs an array of all the items in the sortable with their id's and their current indexes.
Here is a working example on jsfiddle as well: http://jsfiddle.net/beyondsanity/HgDZ9/
According to the docs http://api.jqueryui.com/sortable/#method-toArray I suggest you to use built-in method toArray
.
Example:
$(document).ready(function() {
$('#sortable').sortable({
stop: function(e, ui) {
console.log($('#sortable').sortable('toArray'));
}
});
$('#sortable').disableSelection();
});
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