javascript - Detect Click on Table Row from Generated Table with JQuery -


i trying detect click on table rows, i'm having problems. table generated javascript file , placed inside div inside html.this div named 'tableoutput'. jquery click function work if set 'tableoutput', set '#mytable', or '#mytable tr' not anything. advice? thanks!

code generates 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 detects click:

$(document).ready(function() { $('#dp1').datepicker(); loadusers();  $('#mt tr').on("click", function(){     alert($(this).attr("id")); }); }); 

you need event delegation bind event dynamically added elements. since have static parent of table div id tableoutput can delegate event it.

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

delegated events

delegated events have advantage can process events descendant elements added document @ later time. picking element guaranteed present @ time delegated event handler attached, can use delegated events avoid need attach , remove event handlers, jquery docs


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -