I am trying to insert a hyphen when the input size is exactly two. Here is my code
document.getElementById('numberInput').onkeypress = function() {
if (this.value.length == 2) {
this.value = this.value '-';
}
}
<input type="text" id="numberInput">
But the problem is the - doesn't appears until third character is inputted. Although the hyphen is placed properly, i mean after two characters.
How can i get hyphen right after entering two characters?
I tried onkeyup
but the problem is it also fires when i press backspace button. When there are two characters, the hyphen appears but at that point if I press backspace and delete the hyphen it immediately comes back. So i choose onkeypress
CodePudding user response:
the value of the input text box, during onKeyPress is always the value before the change. This allows the event listener to cancel the keypress.
To get the value after the field value has been updated, schedule a function to run on the next event loop. The usual way to do this is to call setTimeout with a timeout of 0:
document.getElementById('numberInput').onkeypress = function() {
// arrow function keeps scope
setTimeout(() => {
// now it is the value after the keypress
if (this.value.length == 2) {
this.value = this.value '-';
}
}, 0);
}
<input type="text" id="numberInput">
CodePudding user response:
Why not hook onto the input event instead?
document.getElementById("numberInput")
.addEventListener("input", function(e) {
if (e.target.length === 2) {
e.target.value = "-";
}
});
CodePudding user response:
This is happening because of event loop. this.value
is updated only after key press. So in this case you always end up with old state.
I would recommend using other listener method, in this case oninput
.
And retrieving latest input value throughout function parameters
In your case fix would be:
document.getElementById('numberInput').oninput = function (event) {
if (event.target.value.length === 2) {
this.value = event.target.value '-'
}
}