Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I duplicate item when using jquery sortable?

I am using this method http://jqueryui.com/demos/sortable/#connect-lists to connect two lists that i have. I want to be able to drag from list A to list B but when the item is dropped, i need to keep the original one still in list A. I checked the options and events but I believe there is nothing like that. Any approaches?

like image 956
odle Avatar asked Aug 04 '11 11:08

odle


4 Answers

$("#sortable1").sortable({
    connectWith: ".connectedSortable",
    forcePlaceholderSize: false,
    helper: function (e, li) {
        copyHelper = li.clone().insertAfter(li);
        return li.clone();
    },
    stop: function () {
        copyHelper && copyHelper.remove();
    }
});
$(".connectedSortable").sortable({
    receive: function (e, ui) {
        copyHelper = null;
    }
});
like image 199
Erez Avatar answered Nov 07 '22 09:11

Erez


For a beginning, have a look at this, and read @Erez answer, too.

$(function () {
    $("#sortable1").sortable({
        connectWith: ".connectedSortable",
        remove: function (event, ui) {
            ui.item.clone().appendTo('#sortable2');
            $(this).sortable('cancel');
        }
    }).disableSelection();

    $("#sortable2").sortable({
        connectWith: ".connectedSortable"
    }).disableSelection();
});
like image 42
Thorsten Avatar answered Nov 07 '22 08:11

Thorsten


Erez' solution works for me, but I found its lack of encapsulation frustrating. I'd propose using the following solution to avoid global variable usage:

$("#sortable1").sortable({
    connectWith: ".connectedSortable",

    helper: function (e, li) {
        this.copyHelper = li.clone().insertAfter(li);

        $(this).data('copied', false);

        return li.clone();
    },
    stop: function () {

        var copied = $(this).data('copied');

        if (!copied) {
            this.copyHelper.remove();
        }

        this.copyHelper = null;
    }
});

$("#sortable2").sortable({
    receive: function (e, ui) {
        ui.sender.data('copied', true);
    }
});

Here's a jsFiddle: http://jsfiddle.net/v265q/190/

like image 29
Sean Anderson Avatar answered Nov 07 '22 09:11

Sean Anderson


I know this is old, but I could not get Erez's answer to work, and Thorsten's didn't cut it for the project I need it for. This seems to work exactly how I need:

$("#sortable2, #sortable1").sortable({
    connectWith: ".connectedSortable",
    remove: function (e, li) {
        copyHelper = li.item.clone().insertAfter(li.item);
        $(this).sortable('cancel');
        return li.item.clone();
    }
}).disableSelection();
like image 8
abuser2582707 Avatar answered Nov 07 '22 08:11

abuser2582707