Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep track of the positions of all elements in a jQuery sortable

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

like image 296
INT Avatar asked Jul 17 '11 20:07

INT


2 Answers

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/

like image 144
Jesper Haug Karsrud Avatar answered Oct 05 '22 10:10

Jesper Haug Karsrud


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();
  });
like image 27
jmarceli Avatar answered Oct 05 '22 12:10

jmarceli