JavaScript has one important function isNaN() to check any data is number or string. This function isNaN() is remembered as short form is Is Not a Number.
This function returns true if the data is string and returns false if the data is a number.
Here is one simple example to check one string. We will use one if else condition check to display a message accordingly.
<script language='JavaScript' type='text/JavaScript'>
<!--
function disp_data(){
var my_string= document.getElementById('t1').value;
if(isNaN(my_string)){
var str= " :This is Not a number. ";
}else{
var str=" : This is a number. " ;
}
document.getElementById("a2").innerHTML=my_string + str + ", Output of of isNaN = " + isNaN(my_string);
}
//-->
</script>
JavaScript treats empty string as zero , hence isNaN returns True. We can add parseInt to convert string to number before to make isNaN function returns false.
my_string = parseInt(my_string);
Here is the code.
var my_string = prompt("Please enter a number","");
document.write(my_string)
if(isNaN(my_string)){
document.write ("this is not a number ");
}else{document.write ("this is a number ");
}
yes, agree,
this is very useful topic it helps me in project,
good concept not finding in other sites
Dhaval Shingala
25-02-2010
The simplest Way is Why u check entered input is Number or not
just check on Keypress Event is number or not
The Function for checking Is number is
function isNumberKey(B,C){if(!C){C=0}var A=(B.which)?B.which:event.keyCode;if(A>31
Rakesh Joshi
16-04-2010
I observed that isNaN has a flaw. If we enter a value with alphabets at the start, it will detect. But if it starts with a number and continues with alphabets or ends with alphabets, then isNaN will return false, meaning to say it is a number, which is not the desired output. Is there any other alternative?
01-09-2010
write a javascript code that will pop-up when an input of not a number is enter and return true when number data is enter. but without using in inbuild function such as isNan.
angelito
09-06-2012
This is okay..
Ray
30-08-2012
Use Integer.parseInt("value") instead and put that in a try catch block.
san
11-02-2014
@Ray, this is JavaScript not Java.
kamal
07-08-2014
thanx alot very useful
✖
We use cookies to improve your browsing experience. . Learn more