I know a lot of JavaScript, but I am humble enough to recognize that my knowledge of the language is still very incomplete--which is why I'm here asking this question! I have an <input> field that only accepts numerical digits (0 through 9). Of course I have the server-side code stripping out any non-numerical characters, but for convenience, I also use a JavaScript that utilizes an onKeyPress event handler to block any non-numerical characters. It is set up like this:
<input type="text" name="field" id="field" onkeypress="return(numeralsOnly(event));" />
...with the corresponding JavaScript function like this:
function numeralsOnly(evt)
{
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
return true;
}
What I would like to do is use a window.onload function that will dynamically assign the onKeyPress handler to this <input>, rather than having it hard-coded in the HTML. I tried this, and it worked in both Internet Explorer and Opera, but not in Firefox. I think this is because the browsers all handle event's differently. Here's what I tried:
window.onload = function()
{
document.getElementById('field').onkeypress = function() { return(numeralsOnly(event); };
}
Like I said, this seemed to work fine in IE and Opera, but not in Firefox. Any ideas?