Onilol Onilol - 7 months ago 16
Javascript Question

Avoid clone duplication

I'm cloning table rows from one table to another using this:

$("button[name='addItem']").click(function(){
var clone = $(this).closest('tr').clone(true);
clone.appendTo('#items tbody');
})


I'd like to avoid cloning the same item more than once, so I tried something like this:

if(!$.contains("#items tbody",clone)){
clone.appendTo('#items tbody');
}


but it keeps throwing
false
.

Has someone faced this problem?

Answer

Assign data-* to a cloned row and check for that data later

$("button[name='addItem']").click(function(){

  var tr= $(this).closest('tr'); // the TR to clone

  if( tr.data("isCloned") === true) return; // Already cloned!! Stop here

  tr.data("isCloned", true);     // Remember I'm cloned yey!

  var clone = tr.clone(true);    // clone it
  clone.appendTo('#items tbody');
});

Another way using .addClass():

$("button[name='addItem']").click(function(){

  var tr = $(this).closest('tr:not(".isCloned")'); // the TR to clone?

  tr.addClass("isCloned");       // Remember I'm cloned yey!

  var clone = tr.clone(true);    // clone it
  clone.appendTo('#items tbody');
});

the last example might not be obvious but if the selector returns nothing (thanks to the :not() selector) than nothing will be cloned and appended.