Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is jQuery on-click event handler not working properly for dynamic loaded DOM elements?

I load my JavaScript file in the at my home page, then I navigate to the page where I need a onclick function. The onclick is attached to content that has been loaded dynamically over time via AJAX calls. The elements I try to reach are constructed like:

<a href="#" id="query_2" class="list-group-item query">Alle huurdergegevens</a>

And in my JavaScript file I wrote this:

$(".query").click(function() {
    var id = $(this).attr('id');
    id = id.replace(/\D/g,'');
    console.log(id);
    exeSQL(id);
});

When I click the element, literally nothing happens.. Nothing logged in the console, no errors aswell.. Can't figure out what I'm doing wrong tbh..

like image 451
Laurens Mäkel Avatar asked Dec 23 '22 20:12

Laurens Mäkel


1 Answers

when you load any element in DOM after DOM is created then you have to handle click event like this with using on

$(document).on("click",".query",function() {
    var id = $(this).attr('id');
    id = id.replace(/\D/g,'');
    console.log(id);
    exeSQL(id);
});
like image 86
Sagar Arora Avatar answered Dec 31 '22 13:12

Sagar Arora