how to get row index of selected row in table using javascript code example
Example 1: how to get selected row index of table in javascript
<html>
<head>
<title>Row indexes</title>
<script type="text/javascript">
onload = function() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
alert(this.rowIndex + 1);
}
}
}
</script>
</head>
<body>
<table id="my_table">
<tbody>
<tr><td>first row</td></tr>
<tr><td>second row</td></tr>
</tbody>
</table>
</body>
</html>
Example 2: How to get row index and cellindex together in javascript
<html>
<head>
<title>Read Data from HTML Table uisng JavaScript</title>
<style>
th, td, p, input {
font:14px Verdana;
}
table, th, td
{
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<table id="empTable">
<tr>
<th id="id">ID</th>
<th id="emp">Employee Name</th>
<th id="age">Age</th>
</tr>
<tr><td>01</td><td>Alpha</td><td>37</td></tr>
<tr><td>02</td><td>Bravo</td><td>29</td></tr>
<tr><td>03</td><td>Charlie</td><td>32</td></tr>
</table>
<p><select name="select" id="opt">
<option value="">--Select a Value--</option>
<option value="id">ID</option>
<option value="emp">Employee Name</option>
<option value="age">Age</option></select>
</p>
<input type="button" id="bt" value="Show Data" onclick="showTableData()" />
<p id="info" style="font-style:italic;"></p>
</body>
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('empTable');
var opt = document.getElementById("opt").value;
var index = document.getElementById(opt).cellIndex;
for (i = 1; i < myTab.rows.length; i++) {
var objCells = myTab.rows.item(i).cells;
for (var j = index; j <= index; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.innerHTML = info.innerHTML + '<br />';
}
}
</script>
</html>