0

I have a button with the class ".test-class" that when is clicked, a checkbox is created and the message "Clicked" is shown on the console. This works great.

The checkbox must have the same event handler. But I click on the checkbox and the console doesn't show anything. It is like the checkbox doesn't have an event.

This is jQuery Code:

$(".test-class").on("click", function() {
    console.log('Clicked.');
    $("#myDiv").empty().append('<input type=checkbox class=test-class>');
});

This is the button and the div:

<button type="button" class="test-class">Click me</button>
<div id="myDiv">
    <!-- Here will appear a new checkbox. -->
</div>

The Developer's Tool shows the elements:

<button type="button" class="test-class">Click me</button>
<div id="mydiv">
    <input type="checkbox" class="test-class">
</div>

This question is a bit similar.

Roby Sottini
  • 1,652
  • 3
  • 34
  • 64
  • Use Kartikeya Khosla's answer to that question, not the accepted answer. Bind the event to the document and reference your dynamically created element. That should solve your issue. – Aydin4ik Sep 19 '17 at 23:35
  • Check this, you will figure rest by yourself. Also I would advise you to create elements like this in my example in future and bind whatever functions you need to them: http://jsfiddle.net/pegla/rvhhv8sf/7/ – pegla Sep 19 '17 at 23:38

0 Answers0