Autofocus for various fields

0

I have a login form in a modal in bootstrap 4, and I want autofocus in the fields email and password .

<form action="proceso.php" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <input type="email" class="form-control" id="email" name="email" placeholder="Correo electrónico">
    </div>
    <div class="form-group">
        <input type="password" class="form-control" id="password" name="password" placeholder="Contraseña">
    </div>
    <button type="submit" class="btn btn-primary btn-block">Aceptar</button>
</form>

Reading the bootstrap documentation. To put autofocus in the field email I use this, and it works:

<script>
    $('#login').on('shown.bs.modal', function () {
        $('#email').trigger('focus')
    })
</script>

Now I want the focus to go to the password field after ENTER, for this I add the following:

<script>
    $('#login').on('shown.bs.modal', function () {
        $('#password').trigger('focus')
    })
</script>

But when loading the page the focus appears in the second field. What is the problem?

    
asked by Piropeator 25.01.2018 в 23:23
source

2 answers

0

I'll give you a simpler example to apply

$('#campoUser').keyup((e) => {
    if (e.key == "Enter") {
        $('#campoPassword').focus()
    }
})
  

Sometimes it's more easy to do things natively

    
answered by 26.01.2018 / 00:50
source
0

It's like Jhonatan says in the commentary. The problem is that the focus can not be simultaneously in both fields.  - The listener of the modal open should trigger the focus in email  - The listener of the ENTER key (or of the submit of the form, verifying that the password is empty, or something like that) should fire the focus in password.

It is important to do preventDefault to prevent ENTER from triggering an unwanted submit.

    
answered by 26.01.2018 в 00:05