Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Click on Table Row from Generated Table with JQuery

I am trying to detect a click on the table rows, but I'm having problems. The table is generated from a javascript file and is placed inside a div inside the html.This div is named 'tableOutput'. My jquery click function will work if I set it to 'tableOutput', but I set it to '#myTable', or '#myTable tr' it will not do anything. Any advice? Thanks!

Code that generates the table:

function loadUsers() {
$.getJSON("api/users", function(data) {
    var userTable = "\
        <table id=\"mt\" class=\"table table-hover\"><tr><th>User ID</th><th>User Name</th><th>Password</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Phone</th><th>DOB</th><th>Enabled</th></tr>";
    var count = 1;
    $.each(data, function(key, value) {
        userTable = userTable + "<tr id=\"tr" + count + "\"><td>" + value["userID"] + "</td><td>" + value["userName"] + "</td><td>" + value["password"] + "</td><td>" + value["firstName"] + "</td><td>" + value["lastName"] + "</td><td>" + value["email"] + "</td><td>" + value["phone"] + "</td><td>" + value["dateOfBirth"] + "</td><td>" + value["enabled"] + "</td></tr>";
        count = count + 1;
    });
    userTable = userTable + "</table>";
    $("#tableOutput").html(userTable);
}
);
}

Code that detects the click:

$(document).ready(function() {
$('#dp1').datepicker();
loadUsers();

$('#mt tr').on("click", function(){
    alert($(this).attr("id"));
});
});
like image 531
billabrian6 Avatar asked Mar 24 '14 19:03

billabrian6


1 Answers

You need event delegation to bind event to dynamically added elements. Since you have static parent of the table the div with id tableOutput you can delegate event to it.

$('#tableOutput').on("click", '#myTable tr', function(){
    alert($(this).attr("id"));
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery docs

like image 125
Adil Avatar answered Oct 21 '22 08:10

Adil