Search code examples
javascriptjqueryhtml-tableautofocus

Set focus to next input field in a table after maxlength reached


How to set focus to next input field in a table?

Firstly I worked with that JQuery code: But it only works if the input fields are not spread over different and fields. How could I improve it that code or maybe someone knows a JS code that will work for autofocus fields spread over td and tr fields following tabindex?

<script>
$(document).ready(function(){
    $('input').keyup(function(){
        if(this.value.length==$(this).attr("maxlength")){
            $(this).next().focus();
        }
    });
});
</script>

My html:

<table>
<tr>
<td><input type="text" id="field1"  tabindex="1" name="test1" maxlength = "1"></td>
<td><input type="text" id="field2"  tabindex="2" name="test2"  maxlength = "1">.</td>
</tr>
<tr><td><input type="text" id="field3"  tabindex="3" name="test3"  maxlength = "1"></td></tr>
</table>
                 

Solution

  • To do what you require you can retrieve all input elements and get the index of the current one within that collection. To move to the next input, select it from the collection using eq() and the next incremental index value.

    Also note that your HTML is invalid - you seem to be missing a <tr> around the final td. I've corrected that in the following example:

    jQuery($ => {
      let $inputs = $('input').on('input', e => {
        let $input = $(e.target);
        let index = $inputs.index($input);
        if ($input.val().length === $input.prop('maxlength')) {
          $inputs.eq(index + 1).focus();
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <table>
      <tr>
        <td><input type="text" id="field1" tabindex="1" name="test1" maxlength="1"></td>
        <td><input type="text" id="field2" tabindex="2" name="test2" maxlength="1">.</td>
      </tr>
      <tr>
        <td><input type="text" id="field3" tabindex="3" name="test3" maxlength="1"></td>
      </tr>
    </table>