user899628
user899628

Reputation: 279

how to clone an element with specific number of times

what's the syntax to clone an element with assigned times like 5 times? For example, in the html I have this element

<div name="test">
     this is a test
</div>

and I have this clone button which will copy the element once very time I hit it. Then the problem is how can I like just want to copy it 5 times which means after the fifth time I click the copy button, I won't be able to copy the element and get an alart like "already excess maximum "? Thanks in advance!

Upvotes: 1

Views: 1677

Answers (2)

Michael D. Irizarry
Michael D. Irizarry

Reputation: 6302

JS Fiddle
http://jsfiddle.net/DXcQQ/22/

HTML

<div id="content">
    <div name="test" id="item_0">
         this is a test
    </div>
</div>
<button id="btn">Click Me</button>

JS

var maxRows = 5;
var i = 1;

$("#btn").click(function() {     
    if(i < maxRows) {
        $('#item_0').clone().attr("id","item_" + i++).appendTo('#content');
    } else {
        alert('Max Rows Reached!')   
    }
});

Upvotes: 2

Jakub
Jakub

Reputation: 20475

Ummm...

.clone()

... and keep a counter on the number of times you call .clone(). Its very simple.

Example:

var counter = 0;

function clonestuff(){
   if(counter < 5) {
      $(stuff).clone()...
      counter ++;
   } else {
      alert('sorry, excessive cloning detected!');
   }
}

http://api.jquery.com/clone/

Upvotes: 2

Related Questions