neel
neel

Reputation: 5293

Append div more than one time using jquery

http://jsfiddle.net/sF5av/1/

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        
    });
});

enter image description here

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

Answers (4)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Use on() for dynamically added elements like,

$(document).on('click','.btnAdd',function () {
    $('#otheranettedata').append(datatoappend); // end append        
});

Demo

Updated to remove previously added button try this,

$('.btnAdd').length && $('.btnAdd').remove(); 

Updated Demo

Upvotes: 3

codingrose
codingrose

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        
});

Updated fiddle here.

Refer this document.

Upvotes: 4

Robin C Samuel
Robin C Samuel

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

Satpal
Satpal

Reputation: 133403

You need to use event delgation

$(document).on('click', '.btnAdd', function () {
    $('#otheranettedata').append(datatoappend); // end append        
});

DEMO

Upvotes: 3

Related Questions