1

Lets say I have a click event set up for all TRs, naturally each TR is filled with TDs, so when you click a TR you are also clicking a TD. Is there anyway to capture the TD (or its index) that was clicked as a result of a TR being clicked?

I thought perhaps something like this, but I'm not getting anything out of that.

$('tbody').on('click', 'tr', function(){
    var thisEq = $(this+' td').index();
    alert("thisEq: "+thisEq);
});
VikingGoat
  • 387
  • 3
  • 8
  • 30
  • Getting single index of `td` in clicked `tr` doesn't make any sense! If you want index of td you need to click on that td which is ultimately in `tr` – Dhaval Marthak Jul 02 '14 at 16:59
  • possible duplicate of [Getting the ID of the element that fired an event using jQuery](http://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event-using-jquery) – jeremy Jul 03 '14 at 02:56

2 Answers2

3

Demo

You can get the td using event.target

$('tbody').on('click', 'tr', function(e){
    var thisEq = $(e.target).index();
    alert("thisEq: "+thisEq);
});

Note : .index() gives 0 to n values, so you would get 0 for first td

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
-1

Reverse the problem round - detect which td is clicked and detect the parent tr.

$('td').on('click', function(){
    var tr = $(this).parent('tr');
    alert(tr);
 });

You could also do this through use of a delegated event handler. This one hooks onto each tr element but you could hook it onto the body as another submitter has just proposed

 $('tr').on( 'click', 'td', function() {
 ...
 });
vogomatix
  • 4,856
  • 2
  • 23
  • 46
  • 1
    You've given a useless answer... If someone asks "how do I change my settings?" You've essentially answered: "change your settings." – jeremy Jul 02 '14 at 16:58
  • No, I am saying it is an XY problem - you are asking how to do X when Y will give you what you want – vogomatix Jul 02 '14 at 16:59
  • It's not an XY problem at all, unless there are unknown motives behind what the OP is asking. My original comment was for your first answer which was essentially useless... Don't post space fillers and say "this will be filled in a second." – jeremy Jul 02 '14 at 17:01
  • I gave a basic answer to the problem whilst I was improving it - there is nothing wrong with that – vogomatix Jul 02 '14 at 17:02
  • Your answer was, again, rephrasing the question. If someone asks "how do I change my settings?" Again, the answer they're looking for is NOT "change your settings." – jeremy Jul 02 '14 at 17:03
  • He wanted to capture the tr, the td (or its index). My answer achieves both those objectives through looking at it a different way. This is not "change your settings" this is "change how you look at the problem" – vogomatix Jul 02 '14 at 17:05