Link to home
Start Free TrialLog in
Avatar of Whing Dela Cruz
Whing Dela CruzFlag for Anguilla

asked on

Highlighted Row on Keydown or Up

How to make the code below that would be able to highlight to yellow the row when onkeydown press down or up. The code below is working on click, I want it works also in key-down press. Any Help Please!

<!DOCTYPE html>
<html>
<head>
<style>
.selected {
    color: red;
}
</style>

</head>
<body>
<table id="Tab-14">
<thead><th>ID8</th><th>Company</th></thead>
<tbody>
  <tr><td>100</td><td>Peter</td><td><input onkeydown="myIndex(this)" type="text"/></td></tr>
  <tr><td>101</td><td>John</td><td><input onkeydown="myIndex(this)" type="text"/></td></tr>
  <tr><td>102</td><td>Paul</td><td><input onkeydown="myIndex(this)" type="text"/></td></tr>
  <tr><td>103</td><td>Paul</td><td><input onkeydown="myIndex(this)" type="text"/></td></tr>
</tbody>
</table>


<script>
function highlight_row() 
{
	if (document.getElementById("Tab-14")) 
	{
    var table = document.getElementById('Tab-14');
    var cells = table.getElementsByTagName('td');

    for (var i = 0; i < cells.length; i++) {
        // Take each cell
        var cell = cells[i];
        // do something on onclick event for cell
        cell.onclick = function () {
            // Get the row id where the cell exists
            var rowId = this.parentNode.rowIndex;

            var rowsNotSelected = table.getElementsByTagName('tr');
            for (var row = 0; row < rowsNotSelected.length; row++) {
                rowsNotSelected[row].style.backgroundColor = "";
                rowsNotSelected[row].classList.remove('selected');
            }
            var rowSelected = table.getElementsByTagName('tr')[rowId];
            rowSelected.style.backgroundColor = "yellow";
            rowSelected.className += " selected";
        }
    }
	}
	
} 
window.onload = highlight_row;
</script>

<script>
function myIndex(x) 
{
  var t = document.getElementById("Tab-14");
  var ix = x.parentElement.parentElement.rowIndex;
  rc = t.rows.length;

  if (event.keyCode == 38) 
  {
    if (ix != 1)
    {
      t.rows[ix - 1].children[2].children[0].focus();
    }
     
  }
  
  if (event.keyCode == 40) 
  {
    if (ix != rc - 1) 
    {
      t.rows[ix + 1].children[2].children[0].focus();
    }

  }

}
</script>
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Mrunal
Mrunal
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Whing Dela Cruz

ASKER

Hi Mrunal, I do believe your code would lead me to achieve the goal. I will close this question and maybe posted another one with similar issue to make it clear with the experts about  the target. Thank you and more power to you!
The issue is not yet totally resolve, but I do believe that Mrunal Code will lead me to the correct solution. Thank you!