Portal_Zii Portal_Zii - 5 months ago 11
jQuery Question

Cloning divs on click with a remove button - But how do i hide the remove button on the initial clone?

So I have a large button on the left and a form on the right. When you click the button it creates up to 5 additional forms. It also updates the id's and the flavor profile # text.

Its still a little buggy and was looking for some help sorting it out as im not the best with JS.

Problem 1: If you create the 5 additional clones and then delete them. When you create them again it labels them as #7 #8 #9 - Since only 6 forms are allowed. I need this number to only display 1-6 and not go above or below. I would like the same thing for the id's too.

Problem 2: Another issue I have is i would like to remove the "Remove button" from Flavor Profile #1 (The first form). Because if all the forms are deleted there is nothing left to clone.

Thanks for any help!

JS FIDDLE

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

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

var new_clone = $(".clonedInput").first().clone();

new_clone.attr("id", "clonedInput" + cloneIndex);
new_clone.find(".label-nbr").text(cloneIndex);
new_clone.find(".category").attr("id","category"+cloneIndex);
new_clone.show(".remove").attr("id","remove"+cloneIndex);
new_clone.on('click', 'button.clone', clone);
new_clone.on('click', 'button.remove', remove);

$("#formy").append(new_clone);
}
}
function remove(){
if(cloneIndex>1){
$(this).parents(".clonedInput").remove();
cloned_nbr--;
}
}
$(".clone").on("click", clone);

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

Answer

I changed it up a bit. It should work with proper indexes and remove buttons!

function getFreeIds() {
    var used = $('.clonedInput').find('.label-nbr').map(function(i, v) {
            return parseInt(v.innerText)
        }).get();
    return allowed.filter(function (i) {return used.indexOf(i) === -1});
}

It does what you need.

http://jsfiddle.net/tfFLt/1921/

Comments