I'm new to JQuery and I'm having some trouble with the Clone() function.
My question is how can I limit the number of times the answers can be cloned? Would I declare a variable and run it through a loop until the desired number is reached?
Here is the .aspx
> <div id="answer_wrapper">
> <div id="answer">
> <h3 class="new">Answer 1</h3>
> <asp:TextBox ID="QuestionAnswer1" runat="server" CssClass="form" Width="300px"></asp:TextBox>
> </div>
> <h3 class="new">Answer 2</h3>
> <asp:TextBox ID="QuestionAnswer2" runat="server" CssClass="form" Width="300px"></asp:TextBox>
> </div> <!-- end answer_wrapper -->
> <br />
> <asp:Button ID="ga" runat="server" CssClass="button_add_question" style="border: 0px;" />
> <a id="foo" href="#">Duplicate</a>
> <script type="text/javascript">
> $('#foo').click(function () {
> $('#answer').clone().appendTo('#answer_wrapper');
> });
> </script>
Any help would be much appreciated as I don't really know how to approach this.
You can either limit the number of divs cloned by setting a var outside click event and increasing its value or you can count the divs number.
I expect you want to change or remove the id too.
<script type="text/javascript">
var count = 1;
$('#foo').click(function () {
if(count < 5) {
$('#answer').clone().attr({ 'id': 'answer' + count }).appendTo('#answer_wrapper');
//$('#answer').clone().removeAttr('id').appendTo('#answer_wrapper'); // remove the attribute
count++;
}
});
</script>
counting divs:
<script type="text/javascript">
$('#foo').click(function () {
if($('.answer').length < 5) { // Hope you add a class to the answer
$('#answer').clone().addClass('answer').removeAttr('id').appendTo('#answer_wrapper');
}
});
</script>