Prevent drop of list item in JqueryUI sortable

Viewed 29823

I have two lists #sortable1 and #sortable 2 which are connected sortables, as shown in this example.

You can drag and drop list items from sortable1 to sortable 2. However, if an item in sortable 1 contains the class "number", I want to prevent the drop on Sortable2 and thus make the dragged item drop back into sortable 1.

I have used the following on sortable2:

receive: function (event, ui) {
            if ($(ui.item).hasClass("number")) {
                $(ui.item).remove();
            }

but it deletes the list item from both tables altogether. Any help will be appreciated.

8 Answers
beforeStop: function(ev, ui) {
                if ($(ui.item).hasClass('number') && 
                    $(ui.placeholder).parent()[0] != this) {
                    $(this).sortable('cancel');
                }
            }

try this.

If a) you only have just these 2 lists, and b) you don't care that your "number" actually be dragged and then drop back, you can simply prevent it from getting dragged by this:

 sort: function(event, ui) {
if(ui.item.hasClass('number')) return false;
}

Here is my 2 cents. If you don't wish to allow sorting in one of the connected list you can remove it from the containers in the instance object when start even is triggered, so the sorting won't happen at all, and if you need to restore the sorting functionality afterwards, you can recreate the sortable once again or add back removed elements in container array. It would look like this:

    start: function(e, ui){
        if(ui.item.hasClass('uniqToSortableItem')){
            var instance = $(this).sortable( "instance" );
            var newContainers = [];
            instance.containers.forEach((el)=> {
                if(!el.element.hasClass('sortableToDisable')){
                    newContainers.push(el);
                } 
            });
            // in case you need to save initial array just attach it to ui.helper
            ui.helper.initialContainersArray = instance.containers;
            instance.containers = newContainers;
        }
    },
    stop: function(e, ui){
        // returning containers array to previous state if necessary
        if(ui.helper.initialContainersArray){
            $(this).sortable( "instance" ).containers = ui.helper.initialContainersArray;
        }
    }
Related