...

View Full Version : Check for input to be numbers



Lincoln
05-26-2004, 11:55 AM
Hi,
I have created the following codes

function read_display_temp() {
// read temperature here using prompt() function
var q2=prompt("Enter the temperature")

// display temperature on the button
document.q2form.q2button.value=q2+" Degree"

}

How do I make sure that the user enters a number and not letters?

Lincoln

Garadon
05-26-2004, 12:00 PM
I usually check it like this:

if(parseInt(q2,10)==q2){''is a number''}

Spudhead
05-26-2004, 12:36 PM
or

if (!isNAN(q2)){
//its a number
}

glenngv
05-26-2004, 12:46 PM
In prompt dialog, null is returned if the [Cancel] button is clicked. Empty string is returned if [OK] button is clicked while the input is empty. And isNaN('') or isNaN(null) returns false which is wrong.

So it's should be

if (q2!='' && q2!=null && !isNaN(q2)){
//its a number
}

Maybe Garadon's solution is better or using regex is the best.

liorean
05-26-2004, 02:00 PM
null and '' are both turned into 0 when coerced into numbers, so why not just let be treated that way?

Rex
05-26-2004, 03:20 PM
Hello all -

As far as I know, the name of the function is isNaN, not "isNAN".

- Rex

RadarBob
05-26-2004, 04:45 PM
null and '' are both turned into 0 when coerced into numbers, so why not just let be treated that way?
Because it's more clear by explicity checking for the different conditions. Additionally I'd write the check as an independent function seeing how we check for all these different conditions. If/when the language spec changes, we've already encapsulated where our changes will occur.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum