Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom data in jQuery sortable?

on the "update" callback you can get the order of elements with $(this).sortable('toArray');

But this order contains the element IDs.

How can I get a custom attribute, like data-myattr? I want that order to contain values from this attibute instead of IDs....

   $('ul').sortable({
     handle: 'h2'
     items: 'li',
     context: this,
     update: function(){        

       var order = $(this).sortable('toArray');

       // here I want a array of values from my attribute, not ID values...
       alert(order);

       ....

     }
   });

The HTML is simple:

<ul>
  <li data-myattr="a-1" id="whatever">
    ...
  </li>
  ...
like image 586
Alex Avatar asked Nov 24 '11 16:11

Alex


2 Answers

As of August '12, this is implemented directly in jQuery UI:

var order = $(this).sortable('toArray', {attribute: 'data-myattr'});
like image 68
julien_c Avatar answered Sep 27 '22 17:09

julien_c


$("ul").sortable({
  .
  .
  .
  update: function(event, ui) {        
    var arr = $(this).sortable('toArray');
    var i, n;
    var attrs = [];
    for (i = 0, n = arr.length; i < n; i++) {
      attrs.push($('#' + arr[i]).data('myattr'));
    }

    alert(attrs);  
  }
});
like image 30
Luke Girvin Avatar answered Sep 27 '22 18:09

Luke Girvin