user3142695 user3142695 - 10 days ago 5
Javascript Question

Set focus to next input field in a table

I would like to focus the next input in a table field by pressing

enter
.
The table looks like this:

<table>
<tbody>
<tr>
<td>Title 1</td>
<td><input type="number"></td>
<td>Unit</td>
</tr>
<tr>
<td>Title 2</td>
<td><input type="number"></td>
<td>Unit</td>
</tr>
<tr class="group">
<td colspan="3"></td>
</tr>
<tr>
<td>Title 3</td>
<td><input type="number"></td>
<td>Unit</td>
</tr>
<tr class="group">
<td colspan="3"></td>
</tr>
<tr>
<td>Title 4</td>
<td><input type="number"></td>
<td>Unit</td>
</tr>
</tbody>
</table>


And this is my JS to focus the next input field.

'change input[type="number"]': (event) => {
$(event.target).closest('tr').next(':not(.group)').find('input').focus();
}


This is working for the first field. The next input field gets focused. But I can't focus the third input field.

I also tried

'change input[type="number"]': (event) => {
$(event.target).closest('tr').siblings(':not(.group)').find('input').focus();
}


But then the focus is set to the last input field and I don't understand why.

Answer

The problem is that jQuery's next() only looks at the next sibling, not all following siblings. What you want is nextAll():

$(event.target)
    .closest('tr')
    .nextAll('tr:not(.group)')
    .first()
    .find('input')
    .focus();