[JavaScript] Check if Value of Input Text Field is Integer


Yesterday I was writing an online demo for Lemoine’s conjecture [3], I had to check if the value of input text field is integer. If not, the value must be discarded and shows a message to tell users that input must be integer.

After some searches, I found that parseInt() and isNaN() can be used to do the job. The return value of text input field is string. First try parseInt() to convert the value to integer. If the type casting fails, it parseInt() will return NaN, so we can use isNaN() to check the result of conversion.

The following is demo of above idea:



Source Code (HTML)

<input type="text" name="n">
<button type="button" id="check">Check Integer</button><br><br>
<div id="result"></div>

Source Code (JavaScript)

document.querySelector("#check").addEventListener("click", function(e) {
  var n = parseInt(document.querySelector("input[name='n']").value);
  if (isNaN(n)) {
    document.querySelector("#result").innerHTML = "input must be integer";
    return;
  }
  document.querySelector("#result").innerHTML = "integer is " + n;
});

Tested on: Chromium 65.0.3325.181 on Ubuntu 17.10 (64-bit)


References:

[1]
[2]
[3]Online Lemoine’s Conjecture Demo
[4]