I'm new to javascript and I have a couple of questions about functions and events. I'm trying to use the onkeypress object event to test for numbers only in a text field. I can capture the window.event for IE browsers, but I can't seem to capture the DOM object event for other browsers. In other words, when I pass in the event object to my function, e, I can't access any of the properties, such as 'e.charCode' or 'e.which', to determine what key was pressed. Sometimes the IE window.event methods aren't accessible either. Here's some of my code:
//test which browser is being used
var IE = document.attachEvent ? true : false;
var DOM = document.addEventListener ? true : false;
function validateNumber(e) {
var evt = window.event ? window.event : e;
var keyCode = IE ? evt.keyCode : (evt.charCode || evt.which);
evt.cancelBubble = true;
evt.returnValue = false;
if (evt.preventDefault) {evt.preventDefault();}
if (evt.stopPropagation) {evt.stopPropagation();}
}
}
Might anyone have a suggestion why I can't access the charCode or which methods on my 'evt' variable when I run Firefox?
Also, I've tried just passing in the value of a text field to test for a number, and I can't access ANY properties or methods of the parameter (i.e. value.value, value.keyCode, value.charCode), so I can test the pattern against it.
function validateNumber(value) {
var num_pattern = /^\d{1}$/;
var flag = num_pattern.test(value);
}
called from:
Bookmarks