tags:

views:

381

answers:

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?

+1  A: 

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

Ólafur Waage
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.
David Liddle
I actually tried this now, and got the same numbers on both numpad and top keys.
Ólafur Waage
How can I detect the correct key cross-browser and click the respective button. An example is appreciated
Musa
+2  A: 

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.

Jose Basilio
I tested my example above in Firefox, IE and Chrome.
Jose Basilio
Thanks that was spoton!
Musa