Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of elements, jQuery or Javascript

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
})
like image 631
ozsenegal Avatar asked Apr 05 '10 17:04

ozsenegal


2 Answers

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

$("td").click(function() {
  var i = $(this).parent().children().index(this);
  alert(i);
});
like image 136
Nick Craver Avatar answered Nov 01 '22 22:11

Nick Craver


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.

like image 22
jAndy Avatar answered Nov 02 '22 00:11

jAndy