tije
tije

Reputation: 745

JQuery Sortable check array BEFORE drop

I wanted to check the content of target array before I drop an item to the list. Here is the sample: http://jsfiddle.net/steventije/jntnmw2e/

<ul id="sortable1" class="connectedSortable">
    <li class="ui-state-default">Item 1</li>
    <li class="ui-state-default">Item 2</li>
    <li class="ui-state-default">Item 3</li>
    <li class="ui-state-default">Item 4</li>
    <li class="ui-state-default">Item 5</li>
</ul>
<ul id="sortable2" class="connectedSortable">
    <li class="ui-state-highlight">Item 6</li>
    <li class="ui-state-highlight">Item 7</li>
    <li class="ui-state-highlight">Item 8</li>
    <li class="ui-state-highlight">Item 9</li>
    <li class="ui-state-highlight">Item 2</li>
</ul>
<ul id="sortable3" class="connectedSortable">
    <li class="ui-state-highlight">Item 11</li>
    <li class="ui-state-highlight">Item 12</li>
    <li class="ui-state-highlight">Item 13</li>
    <li class="ui-state-highlight">Item 14</li>
    <li class="ui-state-highlight">Item 15</li>
</ul>

$(function () {
    $("#sortable1, #sortable2, #sortable3").sortable({
        connectWith: ".connectedSortable"
    }).disableSelection();
});

Expected behaviour: when I dragged "Item 2" from the first column to the second column, as soon as I drop the item, I want an alert saying that the item has already existed in that column.

UPDATE and OVER do not work the way I expected. Your help is appreciated

Upvotes: 1

Views: 600

Answers (1)

Dhiraj
Dhiraj

Reputation: 33628

Something like this should do

stop: function(evt, ui) {
  var source = ui.item.html(); 
  if (ui.item.closest('ul').find('li:contains(' + source + ')').length > 1) {
    alert(source + ' already exists');
    return false;
  }
}

ui.item.html(); 

will give the text of the currently moving element.

ui.item.closest('ul') 

will give the UL of the container to which the element is being moved to.

.find('li:contains(' + source + ')').length 

will give the number of li elements which have text as the currently moving element.

return false

will revert the item back to original position

Here is a demo http://jsfiddle.net/dhirajbodicherla/jntnmw2e/1/


Update

If the elements have to be checked against ID: (make sure IDs are not repeating)

var source = ui.item.html();
if (ui.item.closest('ul').find('li#' + source).length > 0) { // <--- notice the '0'
  alert(source + ' already exists');
  return false;
}

Upvotes: 2

Related Questions