Question:
How to open the numeric keypad on mobile when typing in input type="text"
? Or when entering input type="number"
to restrict everything except the input of numbers and a comma? The problem is that if there is a dot at the end without a decimal point, input
returns empty. I tried to bind regular expressions, but input type="number"
doesn't react to them at all.
Am I looking for the wrong solution at all? I need that when entering decimal digits on the phone, the numeric keypad opens and everything is considered correctly – when you enter "45."
"45"
was used for calculation, not ""
. Moreover, I noticed that input type="number"
skips a dot, comma and numbers, so when a comma is used, everything is OK – that is, when you enter "45,"
"45"
is taken into account, and when you enter "45."
into the calculation ""
and the result is 0.
Answer:
Since when entering input[type=number]
it does not behave quite adequately when entering a point, I suggest such a crutch with input[type=hidden]
. When submitting the form, take the value from it – the desired value will always be stored there.
A few explanations on the code:
-
At
keydown
event, we catch a click on the dot or the fractional part (the dot on the numpad has a different code) and write the current value + dot toinput[type=hidden]
. We also catch the backspace + check if there is a dot in the penultimate character ininput[type=number]
, and if so, delete the number after the dot. -
The
keyup
event fires after the character has appeared ininput[type=number]
and, if its value istrue
, then we add it toinput[type=hidden]
. If it isfalse
+ the backspace key was pressed + the old value ofinput[type=hidden]
contains one character, then we have erased all characters andinput[type=hidden]
must be set to an empty value. -
The same actions are duplicated on the
input
event so that you can enter the value with the arrows or the mouse wheel.
var input = document.querySelector('input[type=number]'),
hidden = document.querySelector('input[type=hidden]'),
output = document.querySelector('output');
input.addEventListener('keydown', function(e) {
if (e.keyCode === 110 || e.keyCode === 190) {
hidden.value = e.target.value + '.';
} else if (e.keyCode === 8 && e.target.value.slice(-2, -1) === '.') {
hidden.value = hidden.value.slice(0, -1);
}
});
input.addEventListener('keyup', inputProcess);
input.addEventListener('input', inputProcess);
function inputProcess(e) {
if (input.value) {
hidden.value = input.value;
} else if (!input.value && e.keyCode === 8 && hidden.value.length === 1) {
hidden.value = '';
}
output.innerHTML = hidden.value;
}
<input type="number" />
<input type="hidden" />
<br>
<output></output>