SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,338
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    How do you include these conditionals in JS?

    I found the following simple script on the web (I'm barely through my first JS book), and really want to limit what input is possible. Specifically:

    No decimals.
    Only positive numbers.
    Only whole digits 0-9.
    No text.
    No symbols.
    Only accept numbers from 1-200 inclusive.
    No empty fields.

    How do you set the above conditional parameters for the a and b inputs below?

    HTML Code:
    <SCRIPT LANGUAGE="JavaScript">
    function a_div_b(form) {
    a=eval(form.a.value)
    b=eval(form.b.value)
    c=a/b
    form.ans.value = c
    }
    </SCRIPT>
    </head>
    
    <body>
    
    <table>
    <tr>
    <td>
    <FORM name="formx"><input type=number size="4" value="" name="a"> 
    <input type="button" value="  /  " onClick="a_div_b(this.form)">  
    <input type="number" size="4" value="" name="b"> 
    </td>
    </tr>
    <tr>
    <td>
    = <input type "number" value=0 name="ans" size=9>
    </td>
    </tr>
    </FORM>
    </table>
    
    </body>
    This only needs to work on Safari as a web app. Can we make an error message appear in box c if any of the above is wrong, changing the message for each area that's out of bounds?

    Thanks!
    Steve H

  2. #2
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,338
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I tried this but it did not work:

    HTML Code:
    var ntl = "number too low";
    var nth = "number too high";
    var nbf = "no blank fields";
    var numo = "numbers only";
    
    function a_div_b(formx) {
    a=eval(form.a.value)
    b=eval(form.b.value)
     
    if (a, b < 1) 
      { c = ntl };
    if (a, b > 200) 
      {c = nth };
    if (a, b == null) 
      { c = nbf } ;
    if (a, b ! [0-9]) 
      { c = numo };
    if (a, b == [a-z]||[A-Z]) 
     { numo };
     else
     {
    	c=a/b
     };
    form.ans.value = c
    }

  3. #3
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,338
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    This has not been answered, so why is the closed icon appearing in the forum??

  4. #4
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,338
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I got this much to work:

    HTML Code:
    function a_div_b(form) {
    var a=eval(form.a.value);
    var b=eval(form.b.value);
     
    if (a<1 || b<1) 
      { c = "number too low"; }
    else if (a>200 || b>200) 
      { c = "number too high"; }
     else
     {
        c=a/b;
     }
    form.ans.value = c;
    }
    However, I still need to cover the condition if they input a symbol, letter, or decimal.

    Can you help?

    Thanks!
    Steve H

  5. #5
    SitePoint Enthusiast ironikart's Avatar
    Join Date
    Apr 2005
    Posts
    33
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could try a regex to ensure you are dealing with a whole number:

    Code JavaScript:
    function a_div_b(form) {
    var a= form.a.value;
    var b= form.b.value;
    var number = new RegExp('^[0-9]+$');
     
    if (!number.test(a) || !number.test(b)) {
    form.ans.value = 'Only numbers are allowed';
    return;
    }
     
    // Make sure you are dealing with Numbers not Strings
    a = parseInt(a);
    b = parseInt(b);
     
    if (a<1 || b<1) 
      { c = "number too low"; }
    if (a>200 || b>200) 
      { c = "number too high"; }
    if (a==0 || b==0) 
      { c = "do not input 0"; }
     else
     {
    	c=a/b;
     }
    form.ans.value = c;
    }

    Might help to google up some form validation javascript tips - there is metric tons of it on the web. The example you have there doesn't quite feel right with the unnecessary use of eval(), onClick attributes etc, but that's something you can correct over time.

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,688
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by StevenHu View Post
    This has not been answered, so why is the closed icon appearing in the forum??
    When a thread is closed, no replies can be made to it. Since you made a reply to this thread, and as have I, clearly the thread is not closed, which means that a misunderstanding has occurred somewhere.

    Now, on to your form.

    Code html4strict:
    <FORM name="formx">

    First, lowercase tags name please. While uppercase is allowed, it's not acceptable these days.

    For the rest of the form, there is no form field type called "number". The closest you'll get is "text".
    And please enclose attribute values in double quotes, and don't forget to use an equals sign between the attribute name and its value. Thank you.

    Before:
    Code html4strict:
    <input type "number" value=0 name="ans" size=9>

    After:
    Code html4strict:
    <input type="text" value="0" name="ans" size="9">

    Next, the name attribute on the form is performing a useless job. It just does nothing there. If you want a script to easily gain a reference to your form then you should use a unique identifier instead.

    Code html4strict:
    <form id="formx">

    So far as sanitizing the form fields, it can be useful to sanitize them when they are entered, as as part of the onchange event of the field.

    Code javascript:
    var form = document.getElementById('formx');
    form.elements.a.onchange = sanitizeNumber;
    form.elements.b.onchange = sanitizeNumber;

    Now you can modify the entry as need be:

    Code javascript:
    function sanitizeNumber() {
        // restrict to digits only
        this.value = /\d+/.exec(this.value);
        // size check
        if (this.value < 1) {
            this.value = 1;
        }
        if (this.value > 200) {
            this.value = 200;
        }
    }

    With your division button, get rid of the onclick event. That belongs to the early stone-age. Because you cannot target the button as a form field, you can apply a unique identifier to it instead.

    Code html4strict:
    <input id="divide" type="button" value="  /  ">

    Then use a similar technique as before to attach a function to the buttons event.

    Code javascript:
    var divide = document.getElementById('divide');
    divide.onclick = function () {
        a_div_b(form);
    }

    Your a_div_b function can now be very simple indeed.

    Code javascript:
    function a_div_b(form) {
    var a = form.elements.a.value,
        b = form.elements.b.value,
        c = a / b;
        form.elements.ans.value = c;
    }

    Code javascript:
    function sanitizeNumber() {
        // restrict to digits only
        this.value = /\d+/.exec(this.value);
        // size check
        if (this.value < 1) {
            this.value = 1;
        }
        if (this.value > 200) {
            this.value = 200;
        }
    }
     
    function a_div_b(form) {
    var a = form.elements.a.value,
        b = form.elements.b.value,
        c = a / b;
        form.elements.ans.value = c;
    }
     
    var form = document.getElementById('formx');
    form.elements.a.onchange = sanitizeNumber;
    form.elements.b.onchange = sanitizeNumber;
     
    divide.onclick = function () {
        a_div_b(form);
    }

    Here's that script code all put together, which I will reiterate, needs to be placed at the end of the body, just before the </body> tag is the best place for the script.

    Code javascript:
    function sanitizeNumber() {
        // restrict to digits only
        this.value = /\d+/.exec(this.value);
        // size check
        if (this.value < 1) {
            this.value = 1;
        }
        if (this.value > 200) {
            this.value = 200;
        }
    }
     
    function a_div_b(form) {
    var a = form.elements.a.value,
        b = form.elements.b.value,
        c = a / b;
        form.elements.ans.value = c;
    }
     
    var form = document.getElementById('formx');
    form.elements.a.onchange = sanitizeNumber;
    form.elements.b.onchange = sanitizeNumber;
     
    divide.onclick = function () {
        a_div_b(form);
    }

    So far as the error messages are concerned, you can update the answer field from the sanitizeNumber function, and return false to prevent the field from being left until the error is resolved.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,338
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Wow, just wow. This is a real education!

    A couple of clarifications: There is only one form on the page, so I didn't think the name needed anything special. "formx" seemed fine. Nevertheless I'll practice adhering to higher standards and name it appropriately.

    On the iPhone I discovered that if the input type="text", it brings up the text keyboard when you tap on the field. If type="number", it brings up the number keyboard.

    I think I'll change this:
    if (this.value > 200) {
    this.value = 200;
    }

    to:

    if (this.value > 200) {
    this.value = "number is too high";
    }

    I can see the JS book content coming to life in your comments. Based on your reply, I'll update the forms on the other pages.

    Thanks and warmly appreciated!
    Steve H

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,688
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by StevenHu View Post
    On the iPhone I discovered that if the input type="text", it brings up the text keyboard when you tap on the field. If type="number", it brings up the number keyboard.
    That's very interesting, I wasn't aware that the iphone behaves that way.

    Even though it's strictly invalid, it's an interesting extension which is unlikely to break other browsers, due to unknown ones being ignored and the input defaulting to text anyway.

    Quote Originally Posted by StevenHu View Post
    I can see the JS book content coming to life in your comments. Based on your reply, I'll update the forms on the other pages.
    You're welcome. The fundamentals rarely if ever change, which make them excellent building blocks to work with.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

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