Reputation: 13478
I have the following table that returns the each cell value when clicked using javascript?
How can i do the same using jquery?
<script language="javascript">
var tbl = document.getElementById("tblMain");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
</script>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
<tr>
<td>
R2C1
</td>
<td>
R2C2
</td>
<td>
R2C3
</td>
<td>
R2C4
</td>
</tr>
<tr>
<td>
R3C1
</td>
<td>
R3C2
</td>
<td>
R3C3
</td>
<td>
R3C4
</td>
</tr>
<tr>
<td>
R4C1
</td>
<td>
R4C2
</td>
<td>
R4C3
</td>
<td>
R4C4
</td>
</tr>
</table>
Upvotes: 1
Views: 23478
Reputation: 337714
Try this:
$(function() {
$('#tblMain td').click(function() {
alert($(this).html()); // or .text()
});
});
jQuery will internally iterate through all the cells for you, so you don't need any looping code at all.
Upvotes: 1
Reputation: 152294
Try with:
$(document).ready(function(){
var getval = function(html) {
alert(html);
}
$('#tblMain td').on('click', function(){
getval($(this).html());
});
});
Upvotes: 0
Reputation: 41605
Try this:
$('#tblMain').find('td').click(function(){
alert($(this).text());
});
Living demo: http://jsfiddle.net/pf5cL/
Upvotes: 2
Reputation: 104795
How about:
$("#tblMain tr td").click(function() {
var content = $(this).text();
console.log(content); //Cell text
});
Upvotes: 0