Portal_Zii Portal_Zii - 5 months ago 12
jQuery Question

I create a clone of a div on click. The limit is 6 clones. If I delete a clone it breaks the code that limits it?

I have a large button of the left and a form on the right. When you click the button on the left it allows you to create 6 forms in total. That is the set limit and you can not go over it.

Problem #1 - If you select the X icon to delete one of the clones. And then begin adding more clones again. It breaks the set clone limit 1-6 and allows you to create infinite clones.

Problem #2 - How do i remove the X Icon from the first/initial form and only have it "allowed" on its clones.

Thanks!

JS FIDDLE

JS

var clones_limit = 5;
var cloned_nbr = $(".clonedInput").length-1; //Exclude Default (first) div

function clone()
{
if(cloned_nbr<clones_limit)
{
cloned_nbr++;

var new_clone = $(".clonedInput").first().clone();
$("#formy").append(new_clone);
rearrange();
}
}
function remove(){
$(this).parents(".clonedInput").remove();
cloned_nbr--;
rearrange();
}

function rearrange(){
var count = 1;
var totalCount = $(".clonedInput").length;
$(".clonedInput").each(function(){
$(this).attr("id", "clonedInput"+count).find(".label-nbr").text(count).end().
find(".category").attr("id","category"+count).end().find(".remove").toggle(totalCount!=1).attr("id","remove"+count).on("click", remove);
count++;
});
}
$(".clone").on("click", clone);

$(".remove").on("click", remove);

Answer

The problem was with the way you were attaching click event for .remove element. since you were attaching it on create, it used to trigger remove for all the elements recreated and hence decreasing the count of cloned_nbr back to 0. So just remove the click event attaching and make use of event delegation.

Faulty code

function rearrange() {
  var count = 1;
  var totalCount = $(".clonedInput").length;
  $(".clonedInput").each(function() {
    $(this).attr("id", "clonedInput" + count).find(".label-nbr").text(count).end()
    .find(".category").attr("id", "category" + count).end().find(".remove")
    .toggle(totalCount != 1).attr("id", "remove" + count).on("click", remove);
                                                       //^^^this was causing the issue
    count++;
  });
}

Below is the changes, you need to do.

Updated Code

function rearrange() {
  var count = 1;
  var totalCount = $(".clonedInput").length;
  $(".clonedInput").each(function() {
    $(this).attr("id", "clonedInput" + count).find(".label-nbr").text(count).end()
    .find(".category").attr("id", "category" + count).end().find(".remove")
    .toggle(totalCount != 1).attr("id", "remove" + count);
                                                          //^^^No need to attach here
    count++;
  });
}

$(document).on("click", ".remove", remove);//Event delegation

UPDATED FIDDLE HERE


UPDATE - 1

For Problem - 2 Just add below CSS

div[id^="clonedInput"]:first-child .remove{
  display:none;
}

UPDATED FIDDLE 2

Comments