Jquery sortable using UP / Down button

你离开我真会死。 提交于 2019-12-12 15:05:04

问题


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.


回答1:


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/




回答2:


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 */
        }
    }); 
}


来源:https://stackoverflow.com/questions/25978332/jquery-sortable-using-up-down-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!