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.
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/
First, there's no need for the .each
- the .click
method will bind to every passed element, not only the first.
Second, there's a specific properties called cells
on table row elements that gives direct access to the row's cells:
$('.TreeTable').on('click', 'tr', function() {
var td = this.cells[0]; // the first <td>
alert( $(td).text() );
});
Note the use of event delegation - the event handler is actually registered on the entire table, and then relies on event bubbling to tell you which row was clicked (and from that obtain the cell text).
You can get the second cell by using
alert($('td', this).eq(1).text());
Usually, for a more reliable code, you'll prefer to add a class to your desired cell so that you can use
alert($('td.myclass', this).text());
If what you want is to get the cell which was clicked, simply bind the event to the cell :
$(".TreeTable td").click(function() { // td not tr
alert($(this).text());
});
Note that it's useless to loop over a jQuery collection to bind an event, as you can see from my last code.
I prefer this:
$('.TreeTable').on('click', 'td', function() { // td not tr
alert($(this).text());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With