We help IT Professionals succeed at work.

Obtain Row Index on a table

James Lopez
James Lopez asked
on
Hello, I want to get RowIndex on a td using buttons within a table. Is there any body can correct my code?

!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>
	<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<table id="myTable" style="background: #F0FFFF">
	<tr>
    	<td>
        	Ernesto
            <button>RowIndex</button>
        </td>
        <td>Tyson</td>
    </tr>
	<tr>
    	<td>
        	James
            <button>RowIndex</button>
            </td>
        <td>Tejada</td>
    </tr>
	<tr>
    	<td>
        	Mike
            <button>RowIndex</button>
            </td>
        <td>Arnaiz</td>
    </tr>
</table>
	<script>
      $('#myTable').on('click touchstart', 'button', function (e){
          alert(this.parentElement.rowIndex)
          e.preventDefault();
});
    </script>
</body>
</html>

Open in new window

Comment
Watch Question

Analyst Assistant
BRONZE EXPERT
Commented:
James

What exactly do you want to return when one of the buttons is clicked?

'RowIndex' is only the caption for the buttons.

If you want to get the 'index' of the row that contains the button that was clicked you could try something like that.
	<script>
      $('#myTable').on('click touchstart', 'button', function (e){
          alert(this.parentElement.parentElement.rowIndex)
          e.preventDefault();
});
    </script>

Open in new window

Author

Commented:
Thanks sir..