I’ve been having some trouble retrieving text of a table cell that is clicked, the only way I can get the event to fire is substituting “tbody td” with
$("body").click(function(e) {
but this does not return correct data value for cell clicked. Anyone know what I might be doing wrong? I need to create the table using jQuery so it can be dynamically sized based on input given from a form.
$(document).ready(function() {
$('#selection').submit(function() {
$(function () {
var $tbl = $('<table border="1">').attr('id', 'table');
var $tbody = $('<tbody>').attr('id', 'tableBody');
for (var i = 0; i < $("#numOfPieces").val(); i++) {
var trow = $("<tr>"); // New row
for (var j = 0; j < $("#numOfPieces").val(); j++) {
$("<td>")
.text('Row : ' + i + ', Col: ' + j)
.appendTo(trow); // New data cell
}
trow.appendTo($tbody);
}
$tbl.append($tbody);
$('table').remove(); // Remove previously created table
$('body').append($tbl);
});
return false;
});
$("tbody td").click(function(e) {
var currentCellText = $(this).text();
var LeftCellText = $(this).prev().text();
alert(currentCellText);
});
});
The problem is that your click handler is bound to the EXISTING table. You need to bind it to “any” table. In the document ready function:
Where
.containeris any container wrapper element that’s not expected to get destroyed. Make this the closest ancestor you can. If no candidates are available then you can usebody, but I would avoid going this high up if you can.The
tdselector can of course be modified to be more specific if need be. If you have a type of table that this behaviour should be present in, forget about IDs and give that type of table a class. Then thetdjust becomes.someClass tdinstead.You will probably also want to sanitize that your LefCellText even exists before trying to use it. Declaring the variable the way you have it is fine (if there’s no such selector, it just becomes undefined) but you don’t want to assume that you’re going to have the content, you’ll want to create a fallback plan.