January 15, 2016
isNaN() Function in JavaScript
NaN stands for not a number in JavaScript. Floats and integers are basically numbers. IsNaN() function checks whether the value is number or not. It will return true or false. This function will be helpful in case you want to avoid users from passing any value other than a number. Example is given below where we are making use of isNaN() function to detect illegal values before addition.
<html> <head> <title>JavaScript Tutorial </title> <script type="text/javascript"> function getTotal(){ var first = document.getElementById('first') .value; var second = document.getElementById('second') .value; if(isNaN(first)) { alert("Please Check for First Number."); return; } if(isNaN(second)) { alert("Please Check for Second Number."); return; } var total = parseInt(first) + parseInt(second); document.getElementById('total') .value = total; } </script> </head> <body> <input type="textbox" id="first" placeholder="Enter First Number" /> <br /><br /> <input type="textbox" id="second" placeholder="Enter Second Number" /> <br /><br /> <input type="textbox" id="total" placeholder="Total" /> <br /><br /> <input type="button" onclick="getTotal()" value="Get Total"/> </body> </html>