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?

<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

I tried this but it did not work:

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
}

This has not been answered, so why is the closed icon appearing in the forum??

I got this much to work:

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

You could try a regex to ensure you are dealing with a whole number:


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.

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.


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


<input type "number" value=0 name="ans" size=9>

After:


<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.


<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.


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

Now you can modify the entry as need be:


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.


<input id="divide" type="button" value="  /  ">

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


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

Your a_div_b function can now be very simple indeed.


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


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.


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.

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

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.

You’re welcome. The fundamentals rarely if ever change, which make them excellent building blocks to work with.