use F2 to click on jquery button

Asked

Viewed 353 times

3

I have the following button on my website:

<button onclick='document.location="google.com"'>FINALIZAR</button>

How do I make it click when I press F2? I wanted to do this using jquery.

Can someone help me?

4 answers

2


Use the keyup event and check if the keycode is 113 (F2), then just invoke the event of the element you want.

$(document).on('keyup', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 113)
    $('#elemento').trigger('click');
});

$('#elemento').on('click', function () {
  console.log('Disparado evento');  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)" id="elemento" >Exemplo</a>

  • where I get the key codes?

  • 2

    You can give a Google for "Key Codes", but check this link: http://keycode.info/

2

You can identify the event click on the body and if it is F2 click on the button.

$('body').keypress(function(e) {
  var code = e.keyCode || e.which;
  if (code == 113) { // 113 = f2
    $('#btn').click();
  }
});

function finalizar() {
  console.log("Fui clicado");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn" onclick="finalizar()">FINALIZAR</a>

  • 1

    thank you so much for your help.

2

You can do it that way too:

document.onkeyup = KeyCheck;

function KeyCheck(e)
{
    var tecla = (window.event) ? event.keyCode : e.keyCode;
    
    if (tecla == 113) {
      alert('Pressionou F2') // Aqui você coloca seu clique no botão
    }
}

  • 1

    thank you so much for your help.

1

Follows solution:

<button id="finalizar" onclick='document.location="google.com"'>FINALIZAR</button>

$(window).on("keyup", function(event) {
    if (event.keyCode == 113) {
        $("#finalizar").trigger("click");
    }
});
  • thank you so much for your help.

Browser other questions tagged

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