prabu
prabu

Reputation: 6171

Jquery sortable using UP / Down button

I am trying to get sorted order list when user click on 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 getting wrong out and It's not in the user's selected order.

Please suggest me the right way to get sorted order list.

Upvotes: 4

Views: 2975

Answers (2)

Web_Developer
Web_Developer

Reputation: 1251

Due to some reasons, I couldn't see the ids in the new order after change. I did the following changes to the JsFiddle to get ids & 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 */
        }
    }); 
}

Upvotes: 0

Irvin Dominin
Irvin Dominin

Reputation: 30993

The issue is because animate is an async function so your sendOrderToServer function will be fired before the animation complete.

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

Code (of 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/

Upvotes: 4

Related Questions