Search code examples
javascriptfocusnextsibling

Access nextSibling when some inputs are inside parent elements


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!


Solution

  • 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>