2

I have a page with two button. When I press '5' I want that button1 to be clicked and on pressing '6' Button 2 to be clicked. Is it possible using jQuery?

Can I also handle Ctrl+5 in jQuery?

2 Answers 2

3

I recommend binding to the keyup event to prevent event duplicate firings. Here's some sample assuming buttons with Ids, button1 and button2.

$(function() {
    $(document).keyup(function(e) {
       if(e.keyCode == 53 || e.keyCode == 101) { //number 5
          $("#button1").trigger('click');
       } else if(e.keyCode == 54 || e.keyCode == 102) { //number 6
          $("#button2").trigger('click');
       }
   });
});

Trapping CTRL+5 is very tricky and in the case of Chrome, it is intercepted by the browser.

Sign up to request clarification or add additional context in comments.

1 Comment

I tested my example above in Firefox, IE and Chrome.
1

Check out the event helpers in jQuery. Things like keypress and others.

In the keypress demo, when you enter a key into the box, you get to know the charcode number of that key.

For example 5 is 53 and 6 is 64

3 Comments

i've found the charcode is not always correct. press a number key at the top of your keyboard as opposed to the numpad numbers. also try it on different browsers and you get different results.
I actually tried this now, and got the same numbers on both numpad and top keys.
How can I detect the correct key cross-browser and click the respective button. An example is appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.