tags:

views:

64

answers:

3

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
})
+4  A: 

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

$("td").click(function() {
  var i = $(this).parent().children().index(this);
  alert(i);
});
Nick Craver
i dont think so,cause im trying to do this with function(e){}.i.e:e.target.index
@ozsenegal - it works, try it :) http://jsfiddle.net/F5ALE/
Nick Craver
no,thats not quite.Is awalys return "-1".
@ozsenegal - Which browser? It works in all tested here...can click the link to test for yourself.
Nick Craver
its firefox------
@ozsenegal - You're using the *exact* code above? Testing this: http://jsfiddle.net/F5ALE/ in FireFox 3.6.3 works here...
Nick Craver
yes,i just change to:$(e).parent().children().index(this);
@ozsenegal - That changes the entire meaning :) Is your function attached to the `<tr>` or the `<td>`?
Nick Craver
function is attached to all "th" of the first row
@ozsenegal - Then you need to show how it's being attached, if you changed my exact code above and swapped `"th"` for `"td"` it would work. Context is **everything** here, you need to show how the handler you're attaching is coded.
Nick Craver
@ozsenegal - If you leave my example and don't change the `this` the code works with your updated answer still: http://jsfiddle.net/F5ALE/1/ `e` and `this` have **very** different meanings, they are not interchangeable.
Nick Craver
yep,it works now!thk you man
+2  A: 

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.

Kind Regards

--Andy

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

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

gnarf