0

I need to save the sortable items when I refresh the page I didn't know how to do it can any one help me and thanks a lot i used this code

$( "#right_info" ).sortable({
  tolerance: 'pointer',
  cursor: 'move',
  revert: 500,
 });
  • Please look at using window.localStorage to hold a JSON string of your sortable items, in which you can then load the string back as a JSON object using JSON.parse from the localStorage.. – Woodrow May 22 '17 at 21:11
  • thank you but can you show me a code for this problem to solve it – Ashraf Alkassem May 22 '17 at 21:34
  • https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage https://stackoverflow.com/questions/34493531/how-to-store-and-retrieve-json-data-into-local-storage https://stackoverflow.com/questions/23728626/localstorage-and-json-stringify-json-parse – Woodrow May 22 '17 at 21:37
  • @AshrafAlkassem check my answer – Mohamed-Yousef May 23 '17 at 00:32

1 Answers1

0

Finally I got it ..

1st: you need to add data-arrange to your li elements to get the number from it to compare it with the array we will save on local storage

2nd: you need to use localStorage.setItem('sort',data); //to set the array of elements and localStorage.getItem() to get the sort array

So your code should be something like this

HTML

<div class="demo">
    <ul id="sortable">
        <li class="ui-state-default" data-arrange="1"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
        <li class="ui-state-default" data-arrange="2"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
        <li class="ui-state-default fixed" data-arrange="3"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>
        <li class="ui-state-default" data-arrange="4"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 4</li>
        <li class="ui-state-default fixed" data-arrange="5"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 5</li>
        <li class="ui-state-default" data-arrange="6"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 6</li>
        <li class="ui-state-default" data-arrange="7"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 7</li>
    </ul>

</div>

JS

if(localStorage.getItem('sort')){
    var array = localStorage.getItem('sort').split(',');
      map = {},
      el = $('ul');
  alert(array);
  $('ul > li').each(function() { 
      var el = $(this);
      map[el.data('arrange')] = el;
  });
  $('ul').html('');
  for (var i = 0; i <= array.length; i++) {
    if (array[i]) {
        $('ul').append(map[array[i]]);
    }
  }
}; //to get.


$("#sortable").sortable({
    cancel: ".fixed",
    update: function (event, ui) {
        var data = [];
        $('#sortable').find('li').each(function(i) {
            data.push($(this).data('arrange'));
        });
        localStorage.setItem('sort',data); //to set
        }
});
$("#sortable").disableSelection();

Check DEMO Here

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28