How Can I Allow Users To Overwrite The Numbers In The Input Type Number (when There Are Already Two Numbers)?
Solution 1:
I would set the min
and max
properties and then check the validity of the number on input, and set anything out of bounds to either the max or the min.
document.getElementById('num').addEventListener('input', function(e)
{
if(e.target.validity.rangeOverflow)
{
e.target.value = e.target.max;
}
if(e.target.validity.rangeUnderflow)
{
e.target.value = e.target.min;
}
});
<input type="number" min="0" max="99" id="num">
Solution 2:
Perhaps, you could add a handler with timeout that will allow user to continue entering values, but retain only last entered 2 digits.
For snippet to work, below example is pure JS based. It can be extended to be used in Angular code as well.
function maxLengthDay(event) {
setTimeout(() => {
const maxLength = 2;
if (event.target.value.length + 1 > maxLength) {
var v = event.target.value;
event.target.value = event.target.value.substr(v.length - 2, v.length);
}
}, 0);
}
document.addEventListener('keypress', maxLengthDay);
document.addEventListener('paste', maxLengthDay);
<input type="number" />
Solution 3:
From what I have read in the comments I have changed keypress
to input
because of the paste to the input box.
<input type="number" min="0" max="99" (input)="maxLengthDay($event)">
The input is restricted to values between 0 and 99 but that works only for the increment and decrement arrows. It can also be used to determine whether the value has overflow the max value or underflow the min value
If the value is over then it just slice the first two numbers and use them as a value.
If it's under then it's set the min as value.
maxLengthDay(event) {
if(event.target.validity.rangeOverflow) {
event.target.value = event.target.value.slice(0, 2);
}
if(event.target.validity.rangeUnderflow) {
event.target.value = event.target.min;
}
}
Post a Comment for "How Can I Allow Users To Overwrite The Numbers In The Input Type Number (when There Are Already Two Numbers)?"