0

I have problems with the following code I want to append some elements (now for example: buttons; later: this will be input fields) and click on them to do something.

The appending is ok, but by clicking on the new elements (buttons), JQuery doesn't do anything.

In use is jquery-3.3.1.

For example some snippets:

html - before .append:

...
<div class="button">Button</div>
<div class="placeholder"></div>
...

JQuery:

...
$( ".button" ).on("click",function() {
  $('.placeholder').append('<div class="button">Button</div>');
});
...

HTML after .append:

...
<div class="button">Button</div>
<div class="placeholder">
    <div class="button">Button</div>
</div>
...
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
Chris
  • 75
  • 1
  • 9
  • 1
    You should [event delegation](https://learn.jquery.com/events/event-delegation/). `$(document).on("click", ".button",...`. – Mohammad Oct 13 '18 at 11:45
  • Possible duplicate of [Jquery events do not work on dynamically appended elements](https://stackoverflow.com/questions/22131961/jquery-events-do-not-work-on-dynamically-appended-elements) – Mohammad Oct 13 '18 at 11:46

1 Answers1

0

Since the element is being added dynamically, it isn't available when the DOM is first loaded. You have to access them like this;

$(document).on("click","tag",function(){
  // do something
});

In your case

$( "document" ).on("click",".button",function() {
  $('.placeholder').append('<div class="button">Button</div>');
});
Jerdine Sabio
  • 5,688
  • 2
  • 11
  • 23