I was trying to prevent duplicated items from being dragged into #sort2
from #sort
by using a condition to check if there were identical items based on their title attributes in #sort2
. If there was a duplicated, it would remove the old one before appending the new one
$("#sort2").sortable({
receive: function (e, ui) {
var title = ui.item.attr('title');
var img = $('#sort2').find('img[title="'+title+'"]');
console.log(title);
if(img.length)
{
img.remove();
}
ui.sender.data('copied', true);
}
});
But my attempt didn't work, it just removes any item as soon as it is being dragged into #sort2
. Can anyone show me how to do that?
$("#sort").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;
}
});
$("#sort2").sortable({
receive: function (e, ui) {
var title = ui.item.attr('title');
var img = $('#sort2').find('img[title="'+title+'"]');
console.log(title);
if(img.length)
{
img.remove();
}
ui.sender.data('copied', true);
}
});
$('#sort2').on('click','img',function(){
$(this).remove();
});
HTML:
<div class='connectedSortable' id='sort'>
<img title='AAA' src='http://upload.wikimedia.org/wikipedia/commons/7/7f/Wikipedia-logo-en.png'/>
<img title='BBB' src='http://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Wikisource-logo.svg/32px-Wikisource-logo.svg.png'/>
</div>
<div class='connectedSortable' id='sort2'></div>
I found a solution. The original example removes all the images with the same title, so my method is use
img.filter(":gt(0)").remove();
to remove just the first duplicated.Example