Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting an input box to only numbers 0-9 [duplicate]

Tags:

javascript

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>
like image 764
John Smith Avatar asked Aug 09 '13 22:08

John Smith


People also ask

How do I restrict input fields with only numbers?

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.”

Can you restrict the textbox to input numbers only?

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.

How do I restrict numbers in a text box?

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.


2 Answers

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

like image 100
adeneo Avatar answered Oct 24 '22 18:10

adeneo


Using HTML5

<input type="number">

You can also use Modernizr for backwards compatibility

like image 26
doitlikejustin Avatar answered Oct 24 '22 19:10

doitlikejustin