-1

I have a form and I need to fill it with numbers only and I want to not allow typing other characters in the input field using JavaScript.

I need a solution in JavaScript.

  • 1
    Why don't you use ``? – Unmitigated Apr 21 '23 at 06:08
  • Thank you for your response. But I want to learn how to do it using JavaScript. – Harsha Sandakelum Apr 21 '23 at 06:13
  • 1
    Please visit [help], take [tour] to see what and [ask]. Do some research, ***[search for related topics on SO](https://www.google.com/search?q=javascript+allow+only+numbers+in+text+field+site:stackoverflow.com)***; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Apr 21 '23 at 06:33

1 Answers1

-1

You can replace all non-digit characters on the "input" event.

For example:

document.querySelector('input').addEventListener('input', function(e) {
  this.value = this.value.replace(/[^\d]/g, '');
});
<input>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80