Skip to content Skip to sidebar Skip to footer

Add Div's On Click With Counter & Limit

I would like to add some functionality with the below code that only 5 times one can click the add button. Also I would like to add a delete button with every replicated so when c

Solution 1:

You just have to add an if before your duplicate code:

document.getElementById('button').onclick = duplicate;

var original = document.getElementById('duplicater');

var i = 1;

functionduplicate() {
    if (i < 6) {
        varclone = original.cloneNode(true); // "deep" cloneclone.id = "duplicater" + i++; // there can only be one element with an ID
        original.parentNode.appendChild(clone);
    }
}

1. Example on JSFiddle.

If you want to disable the button when 5 times clicked, below is the code:

document.getElementById('button').onclick = duplicate;

var original = document.getElementById('duplicater');

var i = 1;
var max = 5;

functionduplicate() {
    if (i < max + 1) {
        var clone = original.cloneNode(true); // "deep" clone
        clone.id = "duplicater" + i++; // there can only be one element with an ID
        original.parentNode.appendChild(clone);
        if (i > max) document.getElementById('button').disabled = true;
    }
}

2. And an example on JSFiddle.

3. Finally the master solution with add and remove button. But just in a JSFiddle because the code is large...

4. I know it's already a lot but I improved all this, here is the JSFiddle with add and remove button, disable enable function, min max variable and without any i or count varaible, so it's the ultimate master solution ;)

Solution 2:

You can add a button to delete the element like this:

<buttonid="button">Add another plan</button><divid="duplicater"><p>Choose Your Mobile Plan</p><select><optionvalue="1">Package 1</option><optionvalue="2">Package 2</option><optionvalue="3">Package 3</option><optionvalue="4">Package 4</option><optionvalue="5">Package 5</option><optionvalue="6">Package 6</option></select><buttonclass='removebutton'>Delete</button></div>

You can enable a function to fire when it's clicked using jquery:

$('body').on('click', ".removebutton", remove);

Finally, the remove handler can remove the clicked element:

functionremove() {
if (count > 1) {
    if ($(this).parent().attr('id') != 'duplicater') {
        $(this).parent().remove();
        count--;
    } else {
        alert("You can't delete the first plan");
    }
} else {
    alert("You can't delete the first plan");
}
}

http://jsfiddle.net/JVzCt/

I've used a similar approach to the counter as used by ReeCube.

As this uses jquery, you need to include it, either from your local machine or from somewhere else e.g.

<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

All the js code should be wrapped in the standard jquery ready function:

$(function(){
    // Put your js code here.
}); 

Post a Comment for "Add Div's On Click With Counter & Limit"