Bhushan Bhushan - 21 days ago 6
jQuery Question

How to find out which table row was clicked using jQuery?

I am using 'live' function to do some on-click stuff on table rows, i.e.

$("tr").live('click',function() {
alert('Some table row is clicked');
});


I want to find out which row is clicked and using
if-else
, give some custom alert based upon that. Can anyone tell me how to do it?

Thanks a lot.

EDIT 1:

Is there a way by which I can refer to the elements of the clicked row inside the function?

Answer
$("tr").live('click', function() {
    if (this.id == "foo") {
        alert('the tr with the foo id was clicked');
    }
});​

If you want to check which row number, use index:

$("tr").live('click', function() {
   if $(this).index() === 2) {
     alert('The third row was clicked'); // Yes the third as it's zero base index
   }
});​

Live demo


Update:

$("tr").live('click', function() {
    // "this" is the clicked <tr> element
    // $(this).find('td span') is the spans inside a td inside the clicked <tr>
}