How to assign a HotKey with JQuery to a button

2

This is the code of my button in HTML with CSS I would like to use JS to assign it instead of clicking for example a F7 or F8 or any combination of keys with jQuery .

<div class="form-group">
    <button type="submit" class="btn btn-success btn-flat">Guardar</button>
</div>
    
asked by WilsonicX 16.07.2018 в 23:30
source

2 answers

1

Adding to the previous answer. I leave you a basic example, with the combination of keys "ctrl + a"

HTML

  <div class="form-group">
            <button type="submit" id="btn_principal" class="btn btn-success btn-flat">Guardar</button>
 </div>

JS

 document.addEventListener('keyup', event => {
     // combinación de teclas ctrl + a
      if (event.ctrlKey && event.keyCode === 65) {
           document.getElementById("btn_principal").click();
      }
    }, false)

You can search the key codes in link

I also recommend you investigate the keyboard events, since there are several.

  • onkeydown : Corresponds to pressing a key and not releasing it.
  • onkeypress : Corresponds to the keystroke itself.
  • onkeyup : Corresponds to releasing a key that was pressed.

Source: link

    
answered by 16.07.2018 / 23:51
source
2

To achieve what you want you should give an id to the button. Then if you do not want the click to work, you can disable it. Finally, it is simply a matter of using the code of the key you want. Something like this:

$(document).on('keydown', function(event) {  
  if(event.which == 118) { // F7
    $("#Guardar").click();
  }
});
$("#Guardar").on('click', function() {
  alert('hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
       <button id="Guardar" type="submit" class="btn btn-success btn-flat" disabled>Guardar</button>
</div>
    
answered by 16.07.2018 в 23:44