Jquery - Make ENTER trigger a button

Asked

Viewed 1,138 times

0

I have a code in Javascript/Jquery that I wanted to also execute the function or when clicking the button, or that the button was triggered with enter when typing. Detail that this is just a test that I’m doing, nothing serious, it’s not a login system or anything like that. Follow the code:

$("#btIr").click(function(){
    const inLogin = $("#inLogin").val();
    const inSenha = $("#inSenha").val();

    if (inLogin === "admin" && inSenha === "jb2303") {
    window.location.href = "cadastro_de_produtos/index.html"

} else {
    alert("Login e/ou senha não conferem");
    $("#inLogin").focus();
    return
}

});

How do I trigger the function by enter as well?

2 answers

2


Generally, you can use the event.keyCode === 13 to check if ENTER has been pressed.

You need to use Event keydown, keyup or keypress for that reason.

Example:

$('#input').on('keydown', function (e) {

  if (e.keyCode === 13) {
      console.log('Você apertou ENTER');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input">

But it’s also possible to simulate this if you have one button with the type equal to submit within a form.

Then just capture the Event submit that form, thus:

$('#form').on('submit', function (e) {

  e.preventDefault();
  
  console.log('apertou o botão ou apertou enter');
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <input type="text" placeholder="Aperte ENTER" />
  <button type="submit">Enviar</button>
</form>

1

To trigger something’s click event, use the method .click() jQuery.

Example:

if(event.keyCode === 13) {
  $('#btn').click();
}

Example in jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.