Davor
Davor

Reputation: 1237

Jquery trigger an event with on() for an appended element

I basically have a list of products and only one of them can be the default one. This is the basic html:

<td>
    Product 1
    <br><span id="defaultProduct1"><a href="#" class="makeDefaultProduct">This product as default?</a></span>
</td>
<td>
    Product 2
    <br><span id="currentDefaultProduct2"><strong>Default product</strong></span>
</td>

With many non default and only one default.

When the user clicks the link to make a product default, it triggers a piece of script that

  1. does some DB stuff via ajax
  2. turns the link into <strong>Default Product</strong>
  3. Turns the previous default into the link

Here's part of the script - the selectors representing the $(the right span there):

$('span[id^="defaultProduct"] a').on("click", function(e) {
    e.preventDefault();
    //(...)
    selectorProduct.empty().append('<strong>Default product</strong>').attr('id', 'currentDefaultProduct'+productId);
    selectorCurrentDefault.empty().append('<a href="#" class="makeDefaultProduct">This product as default?</a></span>').attr('id', 'defaultProduct'+currentDefaultProductId);
});

The issue being that the click event is not triggered when used on an appended link, despite my tries with on(). What am I doing wrong?

Thanks!

Upvotes: 0

Views: 944

Answers (1)

Blender
Blender

Reputation: 298166

Your current event listener is equivalent to .click(). You have to use event delegation:

$('table').on('click', 'span[id^="defaultProduct"] a', function(e) {
    ...
});

Upvotes: 1

Related Questions