I would like to know how to click on a button in an HTML table and get the row and column number returned to me: For example, with the following table:
<table>
<tr>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
</tr>
<tr>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
</tr>
<tr>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
</tr>
</table>
How would I use JavaScript to click on the first button in the second row and have it tell me that I clicked on the first cell in the second row? Does each button need to have a unique id, or not?
Try this:
function getId(element) {
alert("row" + element.parentNode.parentNode.rowIndex +
" - column" + element.parentNode.cellIndex);
}
<table>
<tr>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
</tr>
<tr>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
</tr>
<tr>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
</tr>
</table>