Keyboard Access of table rows
by queryj
HTML
<table>
<thead>
<tr>
<th>FN</th>
<th>LN</th>
<th>Email</th>
<th>Zip</th>
</tr>
</thead>
<tbody>
<tr tabindex="3">
<td>joe</td>
<td>smith</td>
<td>[email protected]</td>
<td>90021</td>
</tr>
<tr tabindex="4">
<td>aaron</td>
<td>dawson</td>
<td>[email protected]</td>
<td>20877</td>
</tr>
<tr tabindex="5">
<td>eric</td>
<td>liberman</td>
<td>[email protected]</td>
<td>64099</td>
</tr>
<tr tabindex="6">
<td>david</td>
<td>tanaka</td>
<td>[email protected]</td>
<td>20889</td>
</tr>
</tbody>
</table>
<div id="hdiv" style="display: block; background-color: rgb(255, 255, 0)">yellow div</div>
<input type="button" value="Check Color" id="btn-go" />
CSS
.selected{
background-color: yellow;
}
JavaScript
// Code goes here
$(function () {
$("table>tbody>tr").on("keyup", function (e) {
console.log("this ", $(this));
if (e.keyCode === 38) {
console.log("up");
var p = $(this).prev();
if (p) {
p.focus();
}
}
if (e.keyCode === 40) {
console.log("down");
var n = $(this).next();
if (n) {
n.focus();
}
}
// Press s to select, and s again to deselect, deselect does not work.
if (e.keyCode === 83) {
if ($(this).hasClass("selected")){
$("tbody>tr").removeClass("selected");
}
else{
$("tbody>tr").removeClass("selected");
$(this).addClass("selected");
}
}
});
$("#btn-go").on("click", function(){
$("tbody>tr").each(function(){
console.log("tr ", $(this).index(), "bg color: ", $(this).css("background-color") );
});
});
});