How do you perform a reset on a JQuery Sortable
Asked Answered
P

4

12

I'm using JQuery Sortable. I'd like to know if it's possible to, after a number of resortings, restore the sortable control back to its original state similar to a form reset. The 'cancel' option only seems to affect the last sort attempt not all of them.

Peake answered 12/12, 2012 at 18:55 Comment(1)
maybe store the default order in a data attribute?Whist
P
23

I personally like doing it this way:

$("#sortable").sortable({config...});
var cache = $("#sortable").html();

On Reset

$("#sortable").html(cache).sortable("refresh");

I tried using .clone() and.children() and even $("#sortable > *), but find caching the .html() the best option.

In my situation, I have two connected lists. One containing current items the user can sort or remove and another list of available items that the user can grab from to add to the "current item" list. I needed a way to reset everything to original state. The above works great.

Paper answered 13/2, 2013 at 14:59 Comment(1)
This solution won't work if you have multiple class based lists as your sources. I am using 2 lists to feed into one - where my selector is a class. Its a shame there isn't an official "reset" which knows the source of each item to go back.Reticular
R
4

this is simple way

$( "#sortable" ).sortable( "cancel" );
Ricci answered 12/1, 2016 at 10:1 Comment(1)
This will only undo the last sorted change. If I sort multiple and then execute this, it won't work for all of themFirehouse
H
3

Store a reference to the original element order then use that to re-order them.

var sortableElements = $("#sortable div");
$("#sortable").sortable();

Now when you want to restore the original sort order, simply append the divs to the #sortable element.

$("#sortable").append(sortableElements);
Humpy answered 12/12, 2012 at 18:58 Comment(0)
V
1

You can cache a copy of the parent on document ready and restore it on reset.

For example, if <ul class="parent"> is your sortable element:

var sortableCache;
$(document).ready(function() {
    ...
    $('ul.parent').sortable({ ... });
    ...
    sortableCache = $('ul.parent').clone(true);
});

On reset, you can do:

$('ul.parent').replaceWith(sortableCache);
Vesicle answered 12/12, 2012 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.