Reputation: 5293
i have
<div id="anettedata">
<div class="lbl">Annette Name</div><div class="txt"><input type="text" /></div>
<input type="button" id="mybtn" class="btnAdd" value="Add Another Annette" />
</div>
<div id="otheranettedata"></div>
and when the "Add Another Annette" click, i want place the same content in the div "anettedata". i have done this using the following jquery
$(document).ready(function () {
var datatoappend='<div class="otherdata">.........<input type="text" /></div>'
$('.btnAdd').click(function () {
$('#otheranettedata').append(datatoappend); // end append
});
});
My problem is that when i am again click on the newly created button "Add Another Annette" i want to place the same content below the newly created div. How can i rewrite this jquery and html to solve this problem please help me.
and i have one more question, when add new set of div, how can we remove "Add Another Annette"button from previous ones
Upvotes: 3
Views: 2822
Reputation: 40639
Use on() for dynamically added elements like,
$(document).on('click','.btnAdd',function () {
$('#otheranettedata').append(datatoappend); // end append
});
Updated to remove previously added button try this,
$('.btnAdd').length && $('.btnAdd').remove();
Upvotes: 3
Reputation: 15699
Use event delegation.
The .on()
method attaches event handlers to the currently selected set of elements in the jQuery object.
Write:
$(document).on('click','.btnAdd',function () {
$(document).find('.btnAdd').remove();
$('#otheranettedata').append(datatoappend); // end append
});
Upvotes: 4
Reputation: 1225
Use jquery's .on method, so that it will bind events appended elements too.
$(document).on('click', '.btnAdd', function () {
$('#otheranettedata').append(datatoappend);
});
Above code will bind function to all elements with class '.btnAdd' in document.
Upvotes: 1