5

Good day,

Im wondering if we can use keyboard shortcut F2 and F3 to execute function. If got, maybe can share your code to me. Below my idea to make the shortcut key. i've tried but not functioning.

$("#ENQUIRY_VIEWMETER").keypress(function(event) {
    if(event.which == 113) { //F2
        updateMtr();
    } else if(event.which == 114) { //F3
        resetView();
    }
});

p/s : or maybe need some amendment on my code. :)

rrk
  • 15,677
  • 4
  • 29
  • 45
hemiz
  • 91
  • 1
  • 2
  • 8

3 Answers3

13

Try using the keydown event instead of keypress. The keydown event tells you which actual key was pressed, but keypress is more about what character resulted.

And return false so that the default browser behaviour (if any) for those keys doesn't go ahead (don't return false for other keys).

$("#ENQUIRY_VIEWMETER").keydown(function(event) {
    if(event.which == 113) { //F2
        updateMtr();
        return false;
    }
    else if(event.which == 114) { //F3
        resetView();
        return false;
    }
});

Demo: http://jsfiddle.net/TTrPp/

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
2

try like this

$(document).keypress(function(e){
   if(e.charCode == 97){
      alert("a");
      return false;
  }
 })

check this jQuery HotKey plugin

Nikson Kanti Paul
  • 3,394
  • 1
  • 35
  • 51
  • 1
    OP wants to know how to test for function keys. `keypress` is the wrong way to do that (otherwise the code in the question would work). – nnnnnn Jul 05 '12 at 07:05
0
document.onkeyup = KeyCheck;

function KeyCheck(e){

   var KeyID = (window.event) ? event.keyCode : e.keyCode;

   if(KeyID == 113){ 

      updateMtr();

   } else if(KeyID == 114) {

       resetView();
    }
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 08 '21 at 06:34
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck – nima Oct 08 '21 at 11:35