Reputation: 1727
I am trying to get the row no and column no of cell on which user has clicked my code is giving the correct column no but row no always giving 0 and 1
I am using the following code help me to find the reason why giving the row no always 0 and 1
<script>
$('td').click(function(){
col = $(this).parent().children().index($(this));
row = $(this).parent().parent().children().index($(this).parent());
alert("row no:"+row+"col no :"+col);
</script>
Upvotes: 1
Views: 10723
Reputation: 256
It is much simpler and faster without jQuery if you use .cellIndex
and .rowIndex
.
$('td').click(function(){
var col = this.cellIndex,
row = this.parentNode.rowIndex;
alert("row no:"+row+"col no :"+col);
As noted by @PatrickRoberts below, old Opera's behavior (version 12 and lower) deviates in that it honors the thead/tbody/tfoot
order in HTML that you provide, so if you put the tfoot
above the tbody
(which is really where it should go), and it has one or more rows, the tbody
rows will be offset by that much.
The correct behavior is to consider the thead
at the top and the tbody
at the bottom, irrespective of where they were defined.
This is no longer an issue in modern Opera since it now uses Chrome's Webkit fork, so the behavior is consistent.
Also note that jQuery's manual .index()
calculation will only take into account the children of the given tbody
, assuming that's the context here.
Upvotes: 1
Reputation: 171679
You can simply use $(element).index()
to get that element's index within it's siblings
$('td').click(function() {
var col = $(this).index(),
row = $(this).parent().index();
console.log("row index:" + row + ", col index :" + col);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
<td>Item 5</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
<td>Item 5</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
<td>Item 5</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
<td>Item 5</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
<td>Item 5</td>
</tr>
</table>
Upvotes: 4