Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click on HTML table and get row number (with Javascript, not jQuery)

Tags:

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?

like image 661
scatterbrain29 Avatar asked Mar 13 '15 21:03

scatterbrain29


People also ask

How can you tell which row number is clicked in a table?

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 () {...}) .

How do I get the index of a row in HTML?

You can use closest('tr') to get the row for current button and use index() to get the index of the row.

How can get row number in HTML table using jquery?

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().


1 Answers

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>
like image 134
Gremash Avatar answered Oct 13 '22 00:10

Gremash