9

How can one restrict an inputbox to just use numbers only.

So if a user were to type in anything from a-z, it will not work in the inputbox.

To some this may seem easy but to me, it sounds like rocket science.

no jQuery please.

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<input type="text" id="numbersonly" />

</body>

</html>
John Smith
  • 1,639
  • 11
  • 36
  • 51
  • 7
    Here's [one duplicate](http://stackoverflow.com/q/469357/778118), and [another](http://stackoverflow.com/q/995183/778118), and [another](http://stackoverflow.com/q/14585407/778118)... This question has been asked dozens of times. – jahroy Aug 09 '13 at 22:55
  • 1

2 Answers2

31

You could use an input with the HTML5 number type

<input type="number" />

or javascript, as an input with a number type doesn't really limit input to numbers only :

document.getElementById('numbersonly').addEventListener('keydown', function(e) {
    var key   = e.keyCode ? e.keyCode : e.which;

    if (!( [8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 ||
         (key == 65 && ( e.ctrlKey || e.metaKey  ) ) || 
         (key >= 35 && key <= 40) ||
         (key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
         (key >= 96 && key <= 105)
       )) e.preventDefault();
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • I encountered a Firefox browser with this proposed solution when entering % or ^ & or *. This solution accepted those characters. Thanks. – Frank May 06 '14 at 03:20
  • 2
    Java Script doesn't work with numeric keys and even doesn't work backspace – Apurva Dec 16 '14 at 07:14
  • 1
    This answer is a good start but has a couple of critical flaws: (1) you cannot use the backspace, delete, or arrow keys to adjust the input, and (2) it allows non-numeric characters when pressing the `shift` or `ctrl` key plus a number (e.g., @, #, $). Have a look at this answer: http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery#answer-995193 – Ryan Burney Dec 09 '15 at 18:19
  • in Typescript keycode is deprecated. can you suggest me another way – R0b1n Jan 17 '20 at 08:54
6

Using HTML5

<input type="number">

You can also use Modernizr for backwards compatibility

doitlikejustin
  • 6,293
  • 2
  • 40
  • 68