...

View Full Version : Javascript Calculator Explaination?



sfarina
10-16-2008, 06:26 PM
I am having issues with identifying the aspects of this script

function checkNum(str) {
for (var i = 0; i < str.length; i++) {
var ch = str.substring(i, i+1)
if (ch < "0" || ch > "9") {
if (ch != "/" && ch != "*" && ch != "+" && ch != "-" && ch != "."
&& ch != "(" && ch!= ")") {
alert("invalid entry!")
return false
}
}
}
return true
}
</script>



could someone please explain to me what each line of this is supposed to do.

Thank you

Philip M
10-16-2008, 06:56 PM
The (rather old-fashioned) script validates an entry so that only numbers 0-9 and certain other symbols
as specified /*+-.() are allowed (a maths formula?):-



<input type = "text" size = "20" name = "txt" onblur = "checkNum(this.value)">

<script type = "text/javascript">

function checkNum(str) { // the value of the variable str (a string) is passed to the function
for (var i = 0; i < str.length; i++) { // loop as many times as the length of the string (number of characters)
var ch = str.substring(i, i+1) // extract the ith character as variable ch
if (ch < "0" || ch > "9") { // if ch is smaller than ASCII 0 or greater than ASCII 9
if (ch != "/" && ch != "*" && ch != "+" && ch != "-" && ch != "." && ch != "(" && ch!= ")") { // if ch is NOT equal to one of the characters specified
alert ("Invalid entry!"); // show the alert
return false; // end the function
} // end if
} // end if
} // end for loop
alert ("OK"); // if conditions not satisfied, i.e. no improper characters found
return true
}
</script>

A simpler version using regular expression is:-


<script type = "text/javascript">
function checkNum(str) {
if (/[^0-9\\\*\+\-\.\(\)]/gi.test(str.value)) {
alert ("Invalid Entry");
return false;
}
}
</script>


Spotted in a toilet in a London office block: TOILET OUT OF ORDER. PLEASE USE FLOOR BELOW



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum