Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only digits to be entered into an input[type="number"] field?

I have an input field in which the user should only be able to enter digits [0-9].

document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
    this.value = this.value.replace(/[^\d]/g, '');
}
<input type="number" id="integer" />

jsFiddle Demo

The problem is this: When I enter a number (eg. 1234) and then press dot (.), + or - the content of the input field is automatically deleted by the browser (value is set to "" = empty string). But why? Changing the type from number to text seems to fix the problem. But then I lose the up/down arrow functionality of the input field. Any ideas?

like image 897
Krisztián Balla Avatar asked Sep 28 '17 13:09

Krisztián Balla


People also ask

How do I allow only numbers in input text field?

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.

How do I restrict the input field to accept only numbers?

You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.

How do you limit the number of input fields?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.


2 Answers

HTML 4 has an event called onkeypress. With that attribute we can do this without using additional JS:

<input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">

Here digits from 0 to 9 are allowed using the event.charCode from 48 to 57.

like image 51
Chamod Pathirana Avatar answered Sep 27 '22 23:09

Chamod Pathirana


The only problem was your input type. Change it to text and it should work !

function validate(e) {
    var charCode = e.keyCode? e.keyCode : e.charCode
    if (!(charCode >= 48 && charCode <= 57)) {
        if(!(charCode>=37 && charCode<=40))
            if(charCode!=8 && charCode!=46)
            return false;
    }
}
<input type="number" id="integer" pattern="[0-9]"
onkeydown="return validate(event)"/>
like image 38
mrid Avatar answered Sep 28 '22 00:09

mrid