I need the help of an expert on my question below as it exceed and goes well beyond the level of knowledge that I have for programming in JavaScript.
Given the existing
I have create a demo using JQuery here on JSBin
In general, we have 2 task:
To highlight the "clicked" row, I use this code
$("#mstrTable tr").click(function(evt){
var element = $(evt.target);
var tableElement = element.parents('table');
tableElement.find('tr').removeClass('highlighted');
element.parents('tr').addClass('highlighted');
});
To choose next/prev row, I use jQuery tree traversal function with some exception when there is no tr
inside your tbody
. Note that keyCode
of left, right, up, down arrow are 37, 39, 38, 40 respectively.
$(document).keypress(function(evt){
var highlightedRow = $("#mstrTable .highlighted");
if (highlightedRow.length > 0) // table cell is selected
{
var tbodyElement = highlightedRow.parents('tbody');
var trElements = tbodyElement.find('tr');
var nextElement = highlightedRow.next('tr');
var prevElement = highlightedRow.prev('tr');
trElements.removeClass("highlighted");
switch(evt.keyCode)
{
case 40:
if(nextElement.length)
{
nextElement.addClass('highlighted');
}
else if (trElements.length)
{
$(trElements[0]).addClass('highlighted');
}
break;
case 38:
if(prevElement.length)
{
prevElement.addClass('highlighted');
}
else if (trElements.length)
{
$(trElements[trElements.length - 1]).addClass('highlighted');
}
break;
}
}
});