Jquery Auto Focus On Next Input Field

Last updated 4 years, 5 months ago | 6034 views 75     5

Jquery | Auto Focus On Next Input Field

The jquery code for autofocus on the next text input field.

$(".input-key").keyup(function() {
   if ($(this).val().length == $(this).attr("maxlength")) {
       $(this).next('.input-key').focus();
      }
});

Let's go through the above jquery code:

"$(this).val().length" keep the real-time value whenever a user releases the pressed key and "$(this).attr(maxLength)" take the value defined in input "maxLength" attribute, after that "$(this).next('.input-key').focus()" move the focus on the next text input field

 


 

Here seen an example with complete code

In this example, there are four input fields. These fields can take up to 4 characters and then the cursor move to the next input fields.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jquery Auto Focus On Next Input Field!</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <!-- Script to move control on next input field -->
    <script>
    $(document).ready(function() {
        $(".input-key").keyup(function() {
            if ($(this).val().length == $(this).attr("maxlength")) {
                $(this).next('.input-key').focus();
            }
        }); 
    });
    </script>
</head>

<body>
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <div class="jumbotron mt-5">
                <h2 class="display-6">Jquery Auto Focus On Next Input Field!</h2>
                <hr>
                <div class="input-group mt-5">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="">Key</span>
                    </div>
                    <input type="text" class="form-control input-key text-center" maxlength="4">
                    <input type="text" class="form-control input-key text-center" maxlength="4">
                    <input type="text" class="form-control input-key text-center" maxlength="4">
                    <input type="text" class="form-control input-key text-center" maxlength="4">
                </div>

            </div>

        </div>
    </div>
</body>

</html>