简体   繁体   中英

Make onKeyDown trigger an HTML button's onClick event

I have a basic HTML form named Calculator, with a button named "btnOne". What I want is for when the user presses the "1" key on the keyboard, the "btnOne" HTML button's onClick event to occur.

To attempt to accomplish this, I placed this function in the Head tag of my document:

<head>
     <SCRIPT LANGUAGE="JavaScript"> 

         //other functions...

        document.onkeydown = function(e){
            if (!e) e = window.event;
            if(e.keycode == '49') {
                document.Calculator.btnOne.click();
            }
            return false;
        }
      </SCRIPT>
</head>

Am I just putting this snippet in the wrong spot? Is there something else I need to do to make the function run? I'm really a beginner with web development and don't know what I'm doing! Of course, once I get figured out how to get this button to work, I will add if statements for all of the other buttons.

check out http://api.jquery.com/category/events/ for a much easier and cleaner way to write this. What you have is basically right, though you'd do well to wrap this in a document ready event, so that the events bind after the dom has loaded.

with jQuery your code would look something like this

jQuery(function() {
    jQuery(window).keypress(function(e){
         if (e.which === 49) {
               jQuery("#btnOne").click();
         }
    });
})

heres a working JS Fiddle that will demonstrate this

http://jsfiddle.net/HXYAD/

However, its probably a good idea to abstract out the event handler for the click into a parameterized function so that you dont have

 jQuery('#btnOne').click(function(){
     //some code
 });

 jQuery('#btnTwo').click(function(){
     //some similar code
 });     
 jQuery('#btnThree').click(function(){
     //some more similar code
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM