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>
Complete HTML/CSS Course 2022 To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field. After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”
By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.
Using <input type="number"> The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.
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
Using HTML5
<input type="number">
You can also use Modernizr for backwards compatibility
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With