user2385136
user2385136

Reputation:

jQuery UI get the sorted position of LI element in UL

I'm using jQuery UI's sortable for my UL list. Each time the user sorts the list, I want each li element to update it's "position" attribute to it's position in the list.

<ul>
<li position="1">a</li>
<li position="2">b</li>
<li position="3">c</li>
</ul>

So when a user swaps c with a, the position will also update. I tried to use .each but it seems that javascript doesn't follow the order of how the LI elements are displayed but the order of the element's creation.

Upvotes: 2

Views: 2028

Answers (3)

ifaour
ifaour

Reputation: 38115

As mentioned in another answer, using update is all you need:

$(function() {
    var $sortable = $('ul').sortable({
        update: function(event, ui) {
            var counter = 1;
            $('li', $sortable).each(function() {
                $(this).attr('position', counter);
                counter++;
            });
        }
    });
});

Example link

Upvotes: 1

Phil.Wheeler
Phil.Wheeler

Reputation: 16848

You'll want to take advantage of the Sortable "update" event:

$( "ul" ).sortable({
   update: function(event, ui) { 
     var order = $(this).sortable('serialize');
     console.info(order);
   }
});

You can then use the "serialize" method to pull the updated order of items. One requirement for this to work is that the IDs of each list item contain an underscore, so you'd want to update your HTML to:

<ul>
   <li id="position_1">a</li>
   <li id="position_2">b</li>
   <li id="position_3">c</li>
</ul>

Upvotes: 0

Tahbaza
Tahbaza

Reputation: 9548

Have you tried :eq selector or index method? Provided you know which li element you're trying to find the position of you could find the position like so:

<ul>
<li id="c">c</li>
<li id="b">b</li>
<li id="a">a</li>
</ul>

var position = $('li#b').index();

Upvotes: 0

Related Questions