Reputation: 35
I need to clone the div and increment the ID's but also limit the number of times cloned to 3. Here is my code:
I have a button that will clone the fields in a div and increment the ID's. This is working fine. I want to add functionality that will only allow the user to clone 3 times; so the output would be <div id="Outer_00">
, <div id="Outer_01">
and <div id="Outer_02">;
then on the 4th button click it would not clone. Here is a jsFiddle: http://jsfiddle.net/Ea5JE/ If the jsFiddle is not working here is the code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
var current_id = 0;
$('#btn').click(function(){
nextElement($('#Outer_00'));
})
function nextElement(element){
var newElement = element.clone();
var id = current_id+1;
current_id = id;
if(id <10)id = "0"+id;
newElement.attr("id",element.attr("id").split("_")[0]+"_"+id);
var field = $('input', newElement).attr("id");
$('input', newElement).attr("id", field.split("_")[0]+"_"+id );
newElement.appendTo($("#elements"));
}
});
</script>
</head>
<body>
<div id="elements">
<div id="Outer_00">
<input type="text" id="Field1_00" value="">
<input type="text" id="Field2_00" value="">
</div>
</div>
<button id="btn">button</button>
</body>
</html>
Any help is appreciated, thanks.
Upvotes: 2
Views: 2874
Reputation: 6234
What about something re-usable, like:
function limit(func, max) {
return function() {
if (max > 0) {
max = max - 1;
return func.apply(this, arguments);
}
};
};
And then:
var nextElement = limit(function(element) {
//function body here
}, 3);
$('#btn').click(function(){
nextElement($('#Outer_00'));
});
Here's a forked version of your fiddle: http://jsfiddle.net/2RHXx/14/
Upvotes: 0
Reputation: 318202
I would just do :
$(document).ready(function() {
$('#btn').click(function(){
var el = $('[id^="Outer_"]');
if ( el.length < 3 ) {
var clone = el.last().clone(true);
clone.children().addBack().prop('id', function(_,ID) {
return ID.slice(0,-1) + (parseInt(ID.slice(-1),10)+1);
}).end().end().appendTo("#elements");
}
});
});
Upvotes: 0
Reputation: 11749
DEMO HERE I would do it like this...
$( document ).ready(function() {
var current_id = 0;
$('#btn').click(function(){
nextElement($('#Outer_00'));
})
function nextElement(element){
if(current_id!=2){
var newElement = element.clone();
var id = current_id+1;
current_id = id;
if(id <3) id = "0"+id;
newElement.attr("id",element.attr("id").split("_")[0]+"_"+id);
newElement.data('id',id);
var field = $('input', newElement).attr("id");
$('input', newElement).attr("id", field.split("_")[0]+"_"+id );
newElement.appendTo($("#elements"));}
}
});
Upvotes: 0
Reputation: 54629
Just add a check to see if you already reached your third element with id=2
$('#btn').click(function(){
if(current_id < 2)
nextElement($('#Outer_00'));
});
Upvotes: 3