Jquery sorted using UP / Down button

I am trying to get a sorted list of orders when the user presses the up / down button. Here is my demo link I workout http://jsfiddle.net/prabud/qy89psbr/

function sendOrderToServer() {
  var items = $(".collection").sortable('toArray');
  var itemList = jQuery.grep(items, function(n, i){
                return (n !== "" && n != null);
        });
}

$(".collection").sortable({ items: ".item" });

$('button').click(function() { 
  var btn = $(this);
  var val = btn.val();
  if (val == 'up')
    moveUp(btn.parents('.item'));
  else
    moveDown(btn.parents('.item'));

  sendOrderToServer();
});

      

Finally, I am wrong and it is not in user selected order.

Please suggest me the correct way to sort the order list.

+3


source to share


2 answers


The problem is that the animate

function is asynchronous, so your function sendOrderToServer

will run before the animation finishes.

You can move the function call inside the full animate callback and it will work.

Code (moveUp):



function moveUp(item) {
    var prev = item.prev();
    if (prev.length == 0) return;
    prev.css('z-index', 999).css('position', 'relative').animate({
        top: item.height()
    }, 250);
    item.css('z-index', 1000).css('position', 'relative').animate({
        top: '-' + prev.height()
    }, 300, function () {
        prev.css('z-index', '').css('top', '').css('position', '');
        item.css('z-index', '').css('top', '').css('position', '');
        item.insertBefore(prev);

        sendOrderToServer();
    });
}

      

Demo: http://jsfiddle.net/IrvinDominin/bvvLurxa/

+3


source


For some reason, I couldn't see the IDs in the new order after the change. I made the following changes in JsFiddle to get ids and send them via ajax to server.



function sendOrderToServer() { 
    var arrayOfIds = $.map($(".item"), function(n, i){
      return n.id;
    });
    $.ajax({
    type: "POST",
    url:  'sortable.php',
    dataType: "json",
    data: { 'item[]': arrayOfIds },
    success: function(data){
            /* Do something */
        }
    }); 
}

      

0


source







All Articles