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
    Sep 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    JS form, compares entered value with set value

    I need a JS script within HTML that will take a numeric value entered into a form, compare whether it is within 2% of a set value, and then return an answer [preferably a pop-up dialogue] saying whether it is or isn't within 2%.

    I've done some really basic C++, HTML, and Perl stuff before, but I'm just highly unfamiliar with the JS language. Any guidance/help would be appreciated!

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,302
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Try this:-

    Code:
    Enter a number:- <input type = "text" id = "mynumber" onblur = "testit()">
    
    <script type = "text/javascript">
    
    function testit() {
    var num = Number(document.getElementById("mynumber").value) || 0;
    // num = parseInt(num,10);  // uncomment if number entered must be an integer
    if (num <=0) {
    alert ("You must enter a number > 0");   // or ("You must enter an integer number > 0"); 
    document.getElementById("mynumber").value = "";
    return false;
    // is there a maximum value allowed?
    }
    
    var setvalue = 100;  // or whatever
    var upper = setvalue *1.02;
    var lower = setvalue *.98;
    if ((num < lower) || (num > upper)) {
    alert ("The number " + num + " you entered is not within 2% of the set value");
    }
    else {
    alert ("The number " + num + " you entered is within 2% of the set value");
    }
    
    }
    
    </script>
    Are the numeric values to be entered real or integer?


    "I find television very educating. The minute somebody turns it on, I go into the library and read a book." -[Groucho Marx, 1890-1977.
    Last edited by Philip M; 09-27-2012 at 07:52 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

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