5

I've a table that contains 3 columns. I need to bind an event that fires off whenever one of those columns is clicked using jQuery.

However, I need to know the index of the column clicked.

i.e: First column (index 0), Second column (index 1), Third column (index 2), and so on...

How can I do that?

var firstRow:

var firstRow = $("tr:first > th", "table[id*=Grid]");

Take a look:

firstrow.click(function(e){
//var id = e.target.index;
var id = $(e).parent().children().index(this);//returns -1
})
2
  • What's firstrow? the <tr>? You need to capture the click on the <td>...a delegate function with `jQuery is the cleanest approach to do that. Commented Apr 5, 2010 at 17:52
  • firstrow,take all "<th>" elements of first row Commented Apr 5, 2010 at 17:57

3 Answers 3

6

You can do this using .index() (it's 0 based), like this:

$("td").click(function() {
  var i = $(this).parent().children().index(this);
  alert(i);
});
Sign up to request clarification or add additional context in comments.

7 Comments

i dont think so,cause im trying to do this with function(e){}.i.e: e.target.index
@ozsenegal - Which browser? It works in all tested here...can click the link to test for yourself.
@ozsenegal - You're using the exact code above? Testing this: jsfiddle.net/F5ALE in FireFox 3.6.3 works here...
@ozsenegal - That changes the entire meaning :) Is your function attached to the <tr> or the <td>?
function is attached to all "th" of the first row
|
2

It might be a better idea to use native javascripts .rowIndex instead of jQuerys .index. jQuery might have some trouble in detecting table head (TH) elements.

3 Comments

How would you use .rowIndex to get the index of a column?
Should be this.cellIndex. But yes: much simpler and more efficient than making jQuery search a node list.
yes, within your click event handler code it is this.rowIndex() / this.cellIndex()
0

I always liked using .prevAll()

$('table').click(function(e) {
  var $targ = $(e.target);
  if ($targ.is('th')) {
    var position = $targ.prevAll().length;
    alert(position);
  }
});

Preview on jsbin

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.