Click to See Complete Forum and Search --> : How do I alert that the user input in not a number?


superwoman
12-05-2002, 08:01 AM
Okay, I'm a little confused. I need to alert if the information that a user submits is in fact a number, if it is not, I have to alert that the values are invalid. Should I use and if statement to do this? Here is my code:

<html>
<head>
<title>calculate interest</title>
</head>
<body>
<script language="Javascript">
function calculateInterest()
{
var principal = parseFloat(document.myForm.principal.value);
var interestRate= parseFloat(document.myForm.interestRate.value);
var numberOfYears= parseFloat(document.myForm.numberOfYears.value);
for (var i = 0; i < numberOfYears; i++)
{
principal = (principal * interestRate) + principal;
}
alert(principal);
}
</script>
<form name="myForm">
<input type="text" name="principal">Principal<br>
<input type="text" name="interestRate">Interest Rate<br>
<input type="text" name="numberOfYears">Number Of Years<br>
<input type="button" value="Calculate" onClick="calculateInterest()">
</form>
</body>
</html>

bmendez
12-05-2002, 10:37 AM
to force that the user type a number i use this script:

function filterNonNumeric(field)
{var result = new String();
var point=0;
var numbers = "0123456789.";
var chars = field.value.split(""); // create array

for (i = 0; i < chars.length; i++)
{
if (numbers.indexOf(chars[i]) != -1)
{if (chars[i]==".")
{point=point+1;}

if (point<=1 && numbers.indexOf(chars[i]) != -1)
{result += chars[i];} } }
if (field.value != result)
field.value = result;
}

and then in the text box you have to use this:
onKeyUp="filterNonNumeric(this);"

like this
<inpyt type=text name="xx" onKeyUp="filterNonNumeric(this);">