-1

I have an html table which is generated dynmically from an ajax call. It can have a variable number of rows and will always have 7 columns.

What I want to know is how to get a td's indexes in the table with JavaScript/JQuery. I'm mostly interested in the column number but the row number would be a bonus.

I have the following handler:

$("#my-table").on("click", "td" ,function () {
    var my_row = $(this).parent();
});
nettux
  • 5,270
  • 2
  • 23
  • 33

2 Answers2

2

You can use cells cellIndex and rows rowIndex property to get x and y position in table.

Try this:

$("#my-table").on("click", "td" ,function () {
  var x=this.cellIndex;
  var y=this.parentNode.rowIndex;
  console.log(x,y);
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
-2

You say "coordinates", but by description of you problem, it appears you want indexes. If I'm correct, then what you want is supper easy. Index is 0 based tho, so if you want a human count, you'll need to add 1.



Keep in mind, when dealing with "dynamic" elements, it's best to use a static parent to assign events. If you don't know a static parent ID, you can always make use of DOM, however, some may recommend against it due to "performance" issues. I've been using $(document) for 6 years now and haven't had a single customer complaint. You decide.

$(document).on("click", "td" ,function () {
    var index_row = $(this).parent().index() + 1,
        index_column = $(this).index() + 1;
    // KEEP IN MIND ^ I added "1" to each as the "index" is "0" based. 
    // See documentation link below
});

Example on jsFiddle

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81