Limiting the input field to numbers 0-9 only

How to limit the input field to only use numbers.

So, if the user must enter anything from az, he will not work in the input field.

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> 
+7
javascript
source share
2 answers

You can use input with type HTML5 number

 <input type="number" /> 

or javascript, since an input with type number doesn't matter really limits only numbers:

 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

+24
source share

Using HTML5

 <input type="number"> 

You can also use Modernizr for backward compatibility.

+7
source share

All Articles