Proper Use of Nan

How would I implement NaN and have Inavlid input display in a

element
To do this I have to use isNaN to verify that numerical values are input.
I just want it to display "Invalid input" whenever a non numeric value is put in either of the two first text boxes.

http://jsfiddle.net/hq3m1uns/1/ this is my fiddle link

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Question2</title>
        <style> 
        
        </style>

        <script type="text/javascript">

    

window.onload = function(){
    
};


 function add_number(){



var first_number = document.querySelector("#tb1").value;
  var second_number = document.querySelector("#tb2").value;
  var First = parseInt(first_number);
  var Second = parseInt(second_number);
  var result = First + Second;
  document.getElementById('tb3').setAttribute("value",result);
}



        </script>


    </head>
    <body>        
        <div>
  <h1>Add two number using text box as input using javascript</h1>
</div>
Enter First Number : <br>
<input type="text" id="tb1" name="TextBox1">
<br> Enter Second Number : <br>
<input type="text" id="tb2" name="TextBox2">
<br> Result : <br>
<input style="width: 50%" type="text" id="tb3" name="TextBox3" >
<br>
<input onclick="add_number()" type="button" id="b1" value="GO" />


</body>
</html>

9 thoughts on “Proper Use of Nan”

  1. One way is to use a keyup event listener on the input field to validate the numeric value and update the textContent of the paragraph element based on its validity.

    Another solution is to use a input type="number" for the input and use HTML5’s checkValidity/reportValidity on it, but I’ll leave that for you to research and learn about on your own.

    function validate(inputId, helpId) {
      var value = document.getElementById(inputId).value;
      var help = document.getElementById(helpId);
      if (isNaN(value))
        help.textContent = "invalid input"
      else
        help.textContent = ""
    }
    Enter First Number : <br>
    <input type="text" id="tb1" name="TextBox1" onkeyup="validate('tb1', 'help1')">
    <p id="help1"></p>
    Reply
  2. Just add a paragraph tag in your HTML file with id "msg" and do the following changes in your javascript code.

    function add_number() {
      var first_number = document.querySelector("#tb1").value;
      var second_number = document.querySelector("#tb2").value;
      
      if (isNaN(first_number) || isNaN(second_number)) {
        document.getElementById('msg').innerHTML = "Invalid Input";
      } else {
        document.getElementById('msg').innerHTML = "";
        var First = parseInt(first_number);
        var Second = parseInt(second_number);
        var result = First + Second;
        document.getElementById('tb3').setAttribute("value", result);
      }
    }
    <p id="msg"></p>
    Reply

Leave a Comment