Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  156] [ 7]  / answers: 1 / hits: 24977  / 11 Years ago, mon, march 25, 2013, 12:00:00

I have an HTML table populated from database.
And a jquery function that adds client click event to every table row.



$(function() {
$(.TreeTable tr).each(function(index) {
$(this).click(function() {
alert($(this).text());
});
});
});


Now I am able to get complete row values by clicking on any row.
Now I need to access individual cell value in that function.
Can any one tell me how I get individual cell value on row click.


More From » jquery

 Answers
44

Take a look at this:



$(document).ready(function(){
$('.TreeTable tr').click(function(e){
var cell = $(e.target).get(0); // This is the TD you clicked
var tr = $(this); // This is the TR you clicked
$('#out').empty();
$('td', tr).each(function(i, td){
$('#out').html(
$('#out').html()
+'<br>'
+i+': '+$(td).text()
+ (td===cell?' [clicked]':'') );
});
});
});


Here is the working code:
http://jsfiddle.net/VbA9D/



In case you have other HTML elements inside the table cells on which you might click, the below example will work better:



$(document).ready(function(){
$('.TreeTable tr').click(function(e){
var cell = $(e.target).get(0); // This is the TD you clicked
if(cell.nodeName != 'TD')
cell = $(cell).closest('td').get(0);
var tr = $(this); // This is the TR you clicked
$('#out').empty();
$('td', tr).each(function(i, td){
$('#out').html(
$('#out').html()
+'<br>'
+i+': '+$(td).text()
+ (td===cell?' [clicked]':'') );
});
});
});


And here is the code you can test:



http://jsfiddle.net/7PWu5/


[#79372] Saturday, March 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarettajb

Total Points: 678
Total Questions: 94
Total Answers: 90

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;