1

I've got a table with tows that are clickable via:

$(".clickableRow").click(function() {
    console.log('Row Clicked');
    window.document.location = $(this).attr("href");
});

That works perfectly after the page is loaded. However, we have added a search function that adds rows dynamically after a Ajax call.

After the call is done, the rows aren't clickable any more.

$('#carName').changeOrDelayedKey(function(e) {
    var carSearch = $(this).val();
    console.log(carSearch);
    var carRows = $('#carTable tr[id^="product-"]');
    $(carRows).each(function () {
            console.log('This:'+this);
            $(this).remove();
    });


    //Get new data
    $.post("search.php", {s: carSearch}, function (data) {
            console.log(data);
            $.each(data, function (index) {
            if ($('#product-' + data[index].externalProductId + '').length == 0) {
                    $('#carTable').append('<tr id="product-' + data[index].externalProductId + '" class="clickableRow" href="/'+data[index].url+'/"><td>' + data[index].title + '</td></tr>');
            }
    });

    }, "json");
   }, 400, 'keyup');

    $(".clickableRow").click(function() {
            console.log('Row Clicked');
    window.document.location = $(this).attr("href");
                    });
Peter Fox
  • 1,043
  • 2
  • 9
  • 24

1 Answers1

2

Dynamically added element could not be recognized by click() function. You must use event delegation like so:

$(document).on('click', '.clickableRow', function() {
    console.log('Row Clicked');
    window.document.location = $(this).attr("href");
});
kapantzak
  • 10,937
  • 4
  • 36
  • 54