//********************function isNumeric()****************
function isNumeric(fieldname, fieldlabel, addchars){
if (addchars == null ) {
var ValidChars = "0123456789.,";
} else {
var ValidChars = "0123456789.," + addchars;
}
var IsNumber=true;
var Char;
for (i = 0; i < fieldname.value.length; i++){
Char = fieldname.value.charAt(i);
if (ValidChars.indexOf(Char) == -1){
alert('Please enter only numbers in ' + fieldlabel);
fieldname.focus();
return false;
}
}
return true;
}
The function is very easy to use. I have a validation function that calls the isNumeric function as follows:
if (!isNumeric(document.forms[0].fatalities,"fatalities in the last 5 years")) return false;The first variable passed it the field that is being checked and the second is a description of the field that is passed to the user if the validation fails. A third variable is optional and would contain additional characters that would be permissible, e.g. "$" or "%". And before you ask, no, I have not tested to make sure that this works in Firefox or Mozilla. To make that work, I would probably have to change the fieldname variable to document.getElementById(fieldname).