Peter Fox
Peter Fox

Reputation: 1315

Binding Click event after append Jquery not working

I've got a modal box that pops up popups when the plus icon is clicked in a table. After the page is loaded five rows are displayed in the table and clicking the plus sign opens the modal box. (Works perfectly).

But now we are changing the content of the table by an AJAX call. Once the TR's are replaced by new ones, the plus signs aren't working any more.

I'm aware of the fact that the event-handler

Table:

<table class="table table-hover" id="carsTable">
    <thead>
    <tr>
        <th>Car Title</th>
        <th>Actions</th>
    </tr>
    </thead>
    <tbody>
        <tr id="car-1836">
            <td>ferrari f50</td>
            <td><a href="#" class="black-modal-80" id="5269327"><i class="glyph-icon icon-plus-circle">+</i></a></td>
        </tr>
    </tbody>
    <tfoot>
    <tr>
        <th>Product Title</th>
        <th>Actions</th>
    </tr>
    </tfoot>
</table>

The Jquery Part that handles the AJAX (and works, replaced the table according to the JSON respons).

$.post("../../../scripts/getCars.php", {s: carSearch}, function (data) {
    $("tr[id='carLoader']").remove();

    $.each(data, function (index) {
        if ($('#selectedCar-' + data[index].externalProductId + '').length == 0) {
            $('#carsTable')
                    .append('<tr id="car-'+ data[index].id+'"><td>' + data[index].title + '</td><td><a href="#" class="black-modal-80" id="' + data[index].externalProductId + '"><i class="glyph-icon icon-plus-circle"></i></a></td></tr>');
        }
    });

}, "json");

Now the event Handler, works after document is ready, but stops working once the AJAX call has replaced the data.

$('#carsTable').on('click', '.black-modal-80', function () {
    console.log('Click detected; modal will be displayed');
});

What's wrong with the binding?

Upvotes: 2

Views: 7446

Answers (1)

Max Sandelin
Max Sandelin

Reputation: 140

When you append something to the window, the element doesn't exist until you run the jQuery. That means the element the click event points to doesn't exist when the click event is defined. So you can use the body as a selector like this.

$('body').on('click', '.black-modal-80', function () {
    console.log('Click detected; modal will be displayed');
});

Hope this helped!

Upvotes: 9

Related Questions