Check If Input Is Number JavaScript

Check If Input Is Number JavaScript

Check If Input Is Number JavaScript

In this Article i will show you how  to  write the code to check whether the User Input is Number in JavaScript

To Write this Code i will use only one  JavaScript Function

  1. document.getElementById().innerHTML .

To Create This Sample, i will need  few things Setup in HTML

  1. A text Box for the User to input
  2. A Button for the User to Submit the Input

I will create one Function

  1. checkNum(numS) -> This Function will check whether the User has enter a numerical Number

 

Check If Input Is Number JavaScript

Input a Number :

How I code The Above

  1. Create the HTML Structure Doc type,  Head, Body Etc , I attached the code in this Blog , feel free to copy it for your reference
  2. Create the Function Call checkNum(numS)
  3. This Function will check  2 things ( (1) Whether the User enter anything (2) Whether the User Enter a Number
  4. I will Use the isNaN() Function
  5. First i will get the User input using the DOM Function numS = document.getElementById(“createNum”).value;
  6. And Save the Value into variable numS
  7. Then i will use isNaN() to check whether the User Enter a Number  , if isNaN() is True , which means that the User  had Enter a non Numeric Number
  8. Then I will check whether the User had enter anything into the text box !numS

The Code is as Below , Feel Free to copy it For your reference


<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">
//This is a New Array
var newArray = [];

// This Fuunction push the enter value into the Array
function checkNum(numS){

numS = document.getElementById("createNum").value;


if(isNaN(numS)){


alert("You did Not enter a Number");

}


else if(!numS) {


alert("You did Not enter anything");

}





else {

alert("You Just Enter a Number");


}


}




</script>
</head>
<body>

<h2>Check If Input Is Number JavaScript</h2>


<P style="color:blue;"><strong>Input a Number :</strong><input type="text" style="text-align:center; margin-left: 10px;" id="createNum" name="element" placeholder="Input A Number" >





<p><input type="button" style="text-align:center; margin-left: 10px;" value="Click & Check" id="" onclick="checkNum(this.numS);"/> </P>




</body>

</html>

&nbsp;

There are tonnes of library and tutorial and explanation on this site , you can check out here

 

Check out how to empty an Array in JavaScript here

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

3 × 2 =