Portal_Zii Portal_Zii - 1 year ago 80
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!


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

function clone()

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

new_clone.attr("id", "clonedInput" + cloneIndex);
new_clone.on('click', 'button.clone', clone);
new_clone.on('click', 'button.remove', remove);

function remove(){
$(".clone").on("click", clone);

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

Answer Source

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)
    return allowed.filter(function (i) {return used.indexOf(i) === -1});

It does what you need.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download