1

I have an Existing div in my Dom that contains a text Box and a Button.When the User clicks the button a new Div is dynamically created that contains a textBox and button.What I want to do is that the button that was clicked should be removed as it is recreated dynamically.

<div id="phone" class="row">    
   <div class="col-md-6">
    <input type="text" name="txtTELEPHONENOs" id="txtTELEPHONENOs"/>
   </div>
<button class= "btnAddMore">Add More</button>
</div>


$(".btnAddMore").click(function () {

    $(this).remove();
    $('#phone').after('<div class="row"><div class="col-md-6"><input type="text"/> </div><button class= "btnAddMore">Add More</button></div>');

});

The problem here is that my Jquery code works only once, It removes the clicked button and recreates it only once.The click function is not executed the second time whereas I want it to work on every click. Please can anyone help me solve this problem?

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Liam Aug 02 '21 at 14:14

2 Answers2

2

You need to Event delegation for attaching events to dynamically added elements:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$("body").on('click','.btnAddMore',function () {
  $(this).remove();
  $('#phone').after('<div class="row"><div class="col-md-6"><input type="text"/> </div><button class= "btnAddMore">Add More</button></div>');
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • Thanks a lot you solution works pefectly! Could you just add a little explanation to why this worked and why not my solution.It'd be a great deal of help to me and others as well. – Vibhesh Kaul Sep 07 '15 at 07:11
0

Dont add your button inside div, so that no need to remove button again and again

<div id="phone" class="row">    
<div class="col-md-6">
 <input type="text" name="txtTELEPHONENOs" id="txtTELEPHONENOs"/>
</div></div>
<button class= "btnAddMore">Add More</button>

$(".btnAddMore").click(function () {
$('#phone').after('<div class="row"><div class="col-md-6"><input type="text"/> </div></div>');
});

check this fiddle ->https://fiddle.jshell.net/e20hc1wo/

Anoop B.K
  • 1,484
  • 2
  • 17
  • 31