Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Oct 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Javascript Calculator Explaination?

    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

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,172
    Thanks
    203
    Thanked 2,549 Times in 2,527 Posts
    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?):-


    Code:
    <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:-

    Code:
    <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
    Last edited by Philip M; 10-16-2008 at 06:01 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •