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
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