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?
First, you should use on now: $('#thetable tr'). on('click', function () {...}) . And perhaps some or all of the table is loaded dynamically, in which case you might try binding to an element you know is present when the DOM is ready, like document : $(document). on('click', '#thetable tr', function () {...}) .
You can use closest('tr') to get the row for current button and use index() to get the index of the row.
You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number: $('td'). click(function(){ var col = $(this). parent().
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With