Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if input is integer using javascript

that's what I have tried :

<html>
<head>
<script>
function myFunction() {
var num = document.getElementById("num").value;
if (Number.isInteger(num)) { 
document.getElementById("show").innerHTML = "Number is integer";
} else {
document.getElementById("show").innerHTML = "Number is not integer";
}
</script>
</head>
<body>
<input id = "num"></input>
<button onclick = "myFunction()">Submit</button>
<p id = "show">Result Appears Here</p>
</body>
</html>

the problem here is that i get "number is not integer" all the time even if the number is integer , the code supposed to check if input is integer or not thanks in advance

like image 527
AmirWG Avatar asked Jun 19 '26 09:06

AmirWG


1 Answers

The value of the #num element is returned as a string as you can see in the console. Just revert it into a number using + sign.

Another thing - you are overwriting the innerHTML attribute of the #num element with every function call. You have to insert the second action document.getElementById("show").innerHTML = "Number is not integer" into the else statement to avoid overwriting.

function myFunction() {
  var num = document.getElementById("num").value;
  console.log(typeof num);

  if (Number.isInteger(+num)) {
    document.getElementById("show").innerHTML = "Number is integer";
  } else {
    document.getElementById("show").innerHTML = "Number is not integer";
  }
}
<input id="num"></input>
<button onclick="myFunction()">Submit</button>
<p id="show">Result Appears Here</p>

There's also another way to check if a number is integer, using modulo.

function myFunction(num) {
  num % 1 ? console.log("Not Integer") : console.log("Integer");
}

myFunction(5);
myFunction(5.5);
like image 148
kind user Avatar answered Jun 20 '26 22:06

kind user