Skip to content Skip to sidebar Skip to footer

Jquery-ui Sortable - Synchronize Array (model) After Update

Let's say I have an array containing data, it would probably come from Ajax (but no need to do this here). With that array I generate the content of a UL element, I make that UL so

Solution 1:

A few changes in the code to get what you are looking for:

var locations = [
  {name: 'point 0', location: [50.8674162,4.3772933]},
  {name: 'point 1', location: [50.8135113,4.3247394]},
  {name: 'point 2', location: [50.8771732,4.3544551]},
  {name: 'point 3', location: [50.8460485,4.3664706]}
];

functiongenerateUl() {
  for(var i in locations) {
    li = $('<li>'+ locations[i].name +' ('+ locations[i].location.toString() +')</li>');
    li.data('d', locations[i])
    $('#points').append(li);
  }
}

$(document).ready(function() {
  generateUl();
  $('#points').sortable({
    update: function(event, ui) {
      new_locations = $(this).find('li').map(function(i, el) {
        return $(el).data('d')
      }).get()
      
      $('#display').html(JSON.stringify(new_locations));
    }
  });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><linkrel="stylesheet"href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"><scriptsrc="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script><ulid="points"></ul><divid="display"></div>
  1. Instead of creating the li content as string - I created li elements and added the data of that point using data('d')
  2. Inside the update function of the sortable object - I got back that data from the li nodes (based on their current position - this is the new order).

Post a Comment for "Jquery-ui Sortable - Synchronize Array (model) After Update"