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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With