0

I'm using jquery sortable, along with a load of custom functions to manage a list. I have functions that trigger the sortable, but I need to change this so that those the sortable only runs if the list has changed in any way.

Is there a way of reading the whole list into a variable, so that I can later compare it with the current list?

Something like this maybe?:

var mylist=$('#myol').attr(ids);

and then later:

if(mylist != $('#myol').attr(ids)) {
    $('#myol').trigger('sortupdate');
}
user4893295
  • 533
  • 6
  • 25
  • See this: https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript – Prashant Saraswat Jun 12 '17 at 19:56
  • See: http://api.jqueryui.com/sortable/#method-toArray returns array of item id's. If you want an string: http://api.jqueryui.com/sortable/#method-serialize and then you can compare the two. – Twisty Jun 12 '17 at 20:16

1 Answers1

0

Here is a simple example based on my comment:

https://jsfiddle.net/Twisty/3x64npfw/

JavaScript

$(function() {
  var preChange, postChange;

  function equalArr(a, b) {
    console.log("Compare", a, b);
    var eq = 0;
    $.each(a, function(k, v) {
      if(a[k] != b[k]){
      eq++;
      }
    });
    return (eq ? false : true);
  }

  $("#sortable").sortable({
    start: function(event, ui) {
      preChange = $(this).sortable("toArray");
    },
    stop: function(event, ui) {
      postChange = $(this).sortable("toArray");
      $(".results").html("After change, the list is the " + (equalArr(preChange, postChange) ? "same." : "different."));
    }
  });
});

This requires that each item in the list has a id attribute. If you're choosing not to use them, you'll want to make a function to iterate the list, read each item, and spit out an array.

function listToArray(target){
  var items = target.children();
  var myArray = [];
  items.each(function(){
    myArray.push($(this).text());
  });
  if(myArray.length == 0){
    return false;
  }
  return myArray;
}
Twisty
  • 30,304
  • 2
  • 26
  • 45