DEV Community

Avnish Jayaswal
Avnish Jayaswal

Posted on

HTML text input allows only numeric input

<h2>JavaScript input filter showcase</h2>
<table>
  <tr>
    <td>Integer</td>
    <td><input id="intTextBox" /></td>
  </tr>
</table>

<script>
  function setInputFilter(textbox, inputFilter) {
    [
      "input",
      "keydown",
      "keyup",
      "mousedown",
      "mouseup",
      "select",
      "contextmenu",
      "drop",
    ].forEach(function (event) {
      textbox.addEventListener(event, function () {
        if (inputFilter(this.value)) {
          this.oldValue = this.value;
          this.oldSelectionStart = this.selectionStart;
          this.oldSelectionEnd = this.selectionEnd;
        } else if (this.hasOwnProperty("oldValue")) {
          this.value = this.oldValue;
          this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
        } else {
          this.value = "";
        }
      });
    });
  }

  setInputFilter(document.getElementById("intTextBox"), function (value) {
    return /^-?\d*$/.test(value);
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Read More: HTML text input allows only numeric input

Top comments (0)