Jarla Jarla - 1 year ago 75
jQuery Question

How can I add a click function to an appended element?

I wonder why my

button is not doing anything:

$(".click").click(function () {
$(".result").append("<tr class='element'><td>element</td><td><button type='button' class='remove'>remove</button></td></tr>");

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody class="result"></tbody>
<button class="click">add element</button>

Answer Source

You need to use delegation when you append elements dynamically.

Call the handler on the static parent/ancestor element, and then pass the element you want to delegate the click event to as the second parameter, like so:

$('.result').on('click', '.remove', function () {
  /* click handling here */
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download