keyup
event is triggered when a key is released. When a key combination is used (e.g. Shift + Tab
) the event will be triggered two or more times depending on the key combination used.
The keyup
event will be triggered twice for the key combination Shift + Tab
. One event for the Shift
and one event for the Tab
.
You can handle this case by writing a condition in the callback function to allow only numbers (considering the OTP will be numeric) by taking the value of the key pressed by the user using the event.key
property.
$("#otp").on("keyup", function (e) {
e.preventDefault();
const pressedKey = e.key;
if (!/^[0-9]+$/.test(pressedKey)) {
return;
}
const inputs = document.querySelectorAll("#otp > *[id]");
let compiledOtp = "";
for (let i = 0; i < inputs.length; i++) {
compiledOtp += inputs[i].value;
}
otp = compiledOtp;
if (otp.length == 4) {
...
});
For more information, please refer to the documentation https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…