I am trying to update a <div>
with a table using jQuery. I want to add a click
handler to each <td>
, but the click
handler will be different for each <td>
. How do you tell which <td>
was clicked if it doenst have a id
?
$(document).ready(function(){
$("button").click(function(){
$.post("controller.php",{ },
function(data){
var obj = JSON.parse(data);
var object;
//add to a table...
var t = "<table id='newstable' class='table table-dark table-hover'><thead><tr><th>Post Subject</th><th>Last Post</th></tr></thead><tbody>";
for (var i = 0; i < obj.length; i++) { // for each row
object = obj[i];
t += "<tr>";
t += "<td colspan='2'>" + object[Object.keys(object)[0]] + "</td>"; // the property value, not the property name
//future lastpost td
t += '</tr>';
}
t += '</tbody></table>';
alert(t);
$("#main-container").html(t);
});
});
});
I understand that in order to get the id you must use this code
$(document).ready(function() {
$("#mycontainer").on('click', '#newtable tbody tr td', function(event) {
alert(event.target.id);
});
});
but what if the id
wasn't set?
Anyone have any recommendations? or guidance? Thanks
I tried to code Daniel Lizik advice and here is what I came up with. It doesnt work. Any ideas how to fix it would be greatly appreciated. thanks.
$(document).ready(function(){
$("#main-container").on('click','#newstable tbody tr td',function(event){
var clickedTd = event.target;
var newsTd;
$("#newstable td").each( function(){
newsTd = $(this);
if(clickedTd == newsTd){
alert("they match");
} else {
alert("no match");
}
});
});
});