1

Suppose I have the following sortable object:

<ul class="photos ui-sortable">
    <li class="photo" data-id="1"></li>
    <li class="photo" data-id="2"></li>
    <li class="photo" data-id="3"></li>
    <li class="photo" data-id="4"></li>
    <li class="photo" data-id="5"></li>
    <li class="photo" data-id="6"></li>
</ul>

Upon sorting, the data-id attribute of all the items need to be updated with their new positions.

I tried this:

$('.photos').sortable({
    stop: function(event, ui){
        $(ui.item).attr('data-id', ui.item.index()+1);
    }
});

But it only updates the data-id of the item that was moved, and not the others. How can I do this?

1
  • 1
    Just out of curiosity, why do you need to do this? The items are indexed by their order in the DOM... Commented Jul 25, 2014 at 14:58

2 Answers 2

15

Use the update event, inside of there just loop over each .photo and set the data-id according to its current index:

$('.photos').sortable({
    update: function(event, ui) {
        $('.photo').each(function(i) { 
           $(this).data('id', i + 1); // updates the data object
           $(this).attr('data-id', i + 1); // updates the attribute
        });
    }
});

Here's a fiddle

Sign up to request clarification or add additional context in comments.

6 Comments

Yes it does , he just haven't updated the data attribute .. in fiddle
@Runcorn My bad I see, nice job
This is nice solution. But what if I remove(delete) any list item. Suppose i drop 5 item in the droppable list (Having data-id='1'...so on) and delete forth element. How to re-arrange ids?
just trigger sortable's update function when the item is deleted
@Nathan that's because in the fiddle only the data object is being updated. jQuery uses the attribute to populate the data object initially, after which there's no association between the two. Here's a fiddle where the attribute is also updated: jsfiddle.net/sk3r8fae
|
4

You are using the stop method ui which returns current item on move. So basically you have to iterate through all the items and manually put the data attribute value ,

$('.photos').sortable({
    stop: function(event, ui){
        $(".ui-sortable li").each(function(i, el){
               $(el).prop('data-id',$(el).index()+1);
        });
    }
});

And here is the Working Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.