Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent drop of list item in JqueryUI sortable

Tags:

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.

like image 888
user1038814 Avatar asked Aug 02 '12 12:08

user1038814


2 Answers

For anyone reading this in future, as mentioned by briansol in comments for the accepted answer, it throws error

Uncaught TypeError: Cannot read property 'removeChild' of null 

The the documentation particularly says

cancel()

Cancels a change in the current sortable and reverts it to the state prior to when the current sort was started. Useful in the stop and receive callback functions.

Canceling the sort during other events is unreliable, So it's better use the receive event as shown in Mj Azani's answer or use the stop event as follows:

$('#list1').sortable({   connectWith: 'ul',   stop: function(ev, ui) {     if(ui.item.hasClass("number"))       $(this).sortable("cancel");    } });   $('#list2').sortable({    connectWith: 'ul', });   

Demo

like image 121
T J Avatar answered Sep 26 '22 17:09

T J


You can use a combination of the stop and sortable('cancel') methods to validate the item being moved. In this example, upon an item being dropped, I check if the item is valid by:

  1. Checking if the item has the class number
  2. and checking if the list item was dropped in list2

This is slightly more hard-coded that I'd like, so alternatively what you could do is check the parent of the dropped item against this, to check if the lists are different. This means that you could potentially have an item of number in list1 and list2, but they're not interchangeable.

jsFiddle Example

$(function() {     $('ul').sortable({         connectWith: 'ul',         stop: function(ev, ui) {             if ($(ui.item).hasClass('number') && $(ui.placeholder).parent()[0] != this) {                 $(this).sortable('cancel');             }         }     });         });​ 
like image 30
Richard Avatar answered Sep 23 '22 17:09

Richard