Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  56] [ 4]  / answers: 1 / hits: 15505  / 8 Years ago, wed, january 27, 2016, 12:00:00

I have a function to test if a prompt input is a number, like so:



function myFunction() 
{
var person = prompt(Please enter your name, );

if (person != null)
{
if(isNaN(person))
{
document.write(hello + person + <br><br>);
}
else
document.write(You gave me a number);

}
else
{
document.write(You didn't answer.<br><br>);
}
}


but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?


More From » javascript

 Answers
6

Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of iNaN hasn't worked properly and I got around the problem by combining the parseInt method with the isNaN method. According to w3schools the isNan('123') should return false and isNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:


var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}

Alternatively you can try this method which is well tested.


function isNumber(searchValue) {
var found = searchValue.search(/^(d*.?d*)$/);
//Change to ^(d*.?d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}

[#63537] Monday, January 25, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malaysias

Total Points: 619
Total Questions: 110
Total Answers: 107

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;