Reputation: 117
If the user clicks a particular column in a html table, how can I get the row and column number of it.
$("table #id").click(function()
{
//get row and column num
});
Upvotes: 0
Views: 209
Reputation: 61083
Assuming that #id
is a td
element:
var myRow = $(this).parent('tr').index();
var myCol = $(this).index();
Of course, more complex table structures require more complex selectors. You'd need to show your HTML for further assistance.
Upvotes: 0
Reputation: 5123
Try the following:
$("table tr td").click(function() {
var rowNo = ($(this).parent().index() + 1);
var cellNo = ($(this).index() + 1);
alert("rowNo=" + rowNo + " || cellNo=" + cellNo);
});
Upvotes: 0
Reputation: 253318
I'd suggest:
$('td').click(function (){
var cell = this,
col = cell.cellIndex + 1,
row = cell.parentNode.rowIndex + 1;
console.log('Row: ' + row + ', column: ' + col)
});
Upvotes: 1
Reputation: 2664
This should be pretty straight forward:
HTML
<p class="result"></p>
<table>
<tr>
<td>row 1 - cell 1</td>
<td>row 1 - cell 2</td>
<td>row 2 - cell 3</td>
</tr>
<tr>
<td>row 2 - cell 1</td>
<td>row 2 - cell 2</td>
<td>row 2 - cell 3</td>
</tr>
<tr>
<td>row 3 - cell 1</td>
<td>row 3 - cell 2</td>
<td>row 3 - cell 3</td>
</tr>
</table>
JS:
var $result = $(".result");
$("table").on("click", "td", function(e) {
var $tableCell = $(this);
var tableCellNumber = $tableCell.index() + 1;
var tableRowNumber = $tableCell.parent().index() + 1;
var result = "row number: " + tableRowNumber + ", cell number: " + tableCellNumber;
$result.text(result);
});
Fiddle: http://jsfiddle.net/Varinder/Rr7JS/
Upvotes: 0