JQuery - Press ENTER to push a button

0

I have a JavaScript / JQuery code that I also wanted to execute the function or click the button, or the button to be pressed with the enter when typing. Detail that this is just a test I'm doing, nothing serious, it's not a login system or anything like that. Here is 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 activate the function by enter too?

    
asked by anonymous 24.10.2018 / 17:38

2 answers

1

Generally, you can use event.keyCode === 13 to check if ENTER was pressed.

You need to use event keydown , keyup or keypress for this.

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><inputtype="text" id="input">

But you can also simulate this if you have button with type equal submit within form .

It is enough to capture the event submit of this form , like this:

$('#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><formid="form">
  <input type="text" placeholder="Aperte ENTER" />
  <button type="submit">Enviar</button>
</form>
    
24.10.2018 / 18:17
0

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

Example:

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

Example on jsfiddle

    
24.10.2018 / 17:47