1

I have jQuery even on button click:

$('button.btn').on('click', function(form)

Sample Exising button after page load:

<button id="5" class="yellow-button btn">Odpublicznij</button>

Works perfectly to all buttons with class btn

But then onclick after ajax request it adds new button to html

content += '<button id="' + comments[i].id + '" class="green-button btn">Upublicznij</button>';

It adds new button like:

<button id="11" class="yellow-button btn">Odpublicznij</button>

And this new button doesn't run this even $('button.btn').on('click', function(form).

And I need it to have this event, not to just be here as a button that doesn't do anything

Krystian Polska
  • 1,286
  • 3
  • 15
  • 27
  • Because you are expecting the code to find the element before it exists. It is like someone calling your name before you enter into the room. You are not going to hear it. – epascarello Jul 03 '17 at 17:16

1 Answers1

2

The issue happens because the new element which you just appended doesn't have that click handler attached to it. Inorder to resolve this, you need to change your selector like

$('body').on('click', 'button.btn', function(form) {
  //code goes here
});

What we are doing here is called Event Delegation.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278