Access nextSibling when some inputs are inside parent elements

71 Views Asked by At

I have a html table where some <input> are inside some <td>. I would like to focus the next input when current input has a value different from "". However this does not work since input elements are not directly following each other

let cells = document.querySelectorAll('td > input');

for (let x of cells) {
  x.maxLength = 1;
  x.type = 'text';
  x.onkeyup = function() {
    if (this.value != '') { this.nextSibling.focus() } //HERE
  }
}
<table>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
</table>

Thanks for help!

1

There are 1 best solutions below

0
On BEST ANSWER

You can just get the index of the current cell and use that instead of the nextSibling.

let cells = document.querySelectorAll('td > input');

for (let x of cells) {
  const index = [...cells].indexOf(x); // Get index of current cell
  
  x.maxLength = 1;
  x.type = 'text';
  x.onkeyup = function() {
    if (this.value != '' && cells[index + 1]) { // Check if the next cell exists
      cells[index + 1].focus(); // Focus next cell
    }
  }
}
<table>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
</table>