0

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.

1 Answer 1

2

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
 });
Sign up to request clarification or add additional context in comments.

4 Comments

This is definitely helping. It's my first try using jQuery, so I think I'm having some trouble with that. I tried putting in this jQuery function, and Firebug is giving me the error message "jQuery is not defined." I do already have an event handler called handleBtnClick that all of the buttons are using.
Also, I put the code in a jsfiddle and it works for half a second, and then the whole form disappers and says: {"error": "Please use POST request"}. Any ideas?
well, if you're getting jQuery is not defined, then you probably havent included a jquery file. docs.jquery.com/Downloading_jQuery could you post the jsFiddle for me to see what you mean?
Thanks guys, with a little playing around and some googling, I got it all working! Thanks a ton

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.