Prevent duplicate element in jQueryUI sortable
I was trying to prevent duplicate elements #sort2
from being dragged in from #sort
by using a condition to check for duplicate elements based on their title attributes in #sort2
. If it was duplicated it will remove the old one before adding a 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 element as soon as it is dragged into #sort2
. Can anyone show me how to do this?
$("#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>
source to share
I found a solution. The original example removes all images with the same title, so my method uses img.filter(":gt(0)").remove();
only the first duplicate to remove.
$("#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.filter(":gt(0)").remove();
}
ui.sender.data('copied', true);
}
});
$('#sort2').on('click','img',function(){
$(this).remove();
});
source to share