JavaScript for Tab Key, Move From One Column to Next Column in a Table Input

Share with Love

Here’s an example of how to implement tab key navigation in a table with input fields in JavaScript:

<script>

let table = document.getElementById(“table-id”);

for (let i = 0; i < table.rows.length; i++) {
for (let j = 0; j < table.rows[i].cells.length; j++) {
let cell = table.rows[i].cells[j];
let input = cell.getElementsByTagName(“input”)[0];
if (input) {
input.addEventListener(“keydown”, function(event) {
if (event.key === “Tab”) {
event.preventDefault();
if (j === table.rows[i].cells.length – 1) {
if (i === table.rows.length – 1) {
table.rows[0].cells[0].getElementsByTagName(“input”)[0].focus();
} else {
table.rows[i + 1].cells[0].getElementsByTagName(“input”)[0].focus();
}
} else {
table.rows[i].cells[j + 1].getElementsByTagName(“input”)[0].focus();
}
}
});
}
}
}

</script>

This code first gets a reference to the table using its id, then loops through each row and cell to find any input fields. If an input field is found, it adds an event listener for the keydown event that listens for the tab key. When the tab key is pressed, the event’s default behavior is prevented, and the focus is moved to the next cell’s input field or to the first cell’s input field if it’s the last cell in the table.