Improve OTP code input

This commit is contained in:
Pierre HUBERT 2022-11-12 18:04:27 +01:00
parent bfe65b0216
commit 5300b1a8f9

View File

@ -15,12 +15,12 @@
<input type="hidden" id="code" name="code"/>
<div class="form-group">
<div id="otp" class="inputs d-flex flex-row justify-content-center mt-2">
<input class="m-2 text-center form-control rounded" type="text" id="i1" maxlength="1" autofocus/>
<input class="m-2 text-center form-control rounded" type="text" id="i2" maxlength="1"/>
<input class="m-2 text-center form-control rounded" type="text" id="i3" maxlength="1"/>
<input class="m-2 text-center form-control rounded" type="text" id="i4" maxlength="1"/>
<input class="m-2 text-center form-control rounded" type="text" id="i5" maxlength="1"/>
<input class="m-2 text-center form-control rounded" type="text" id="i6" maxlength="1"/>
<input class="m-2 text-center form-control rounded" type="text" id="i1" maxlength="6" autofocus/>
<input class="m-2 text-center form-control rounded" type="text" id="i2" maxlength="6"/>
<input class="m-2 text-center form-control rounded" type="text" id="i3" maxlength="6"/>
<input class="m-2 text-center form-control rounded" type="text" id="i4" maxlength="6"/>
<input class="m-2 text-center form-control rounded" type="text" id="i5" maxlength="6"/>
<input class="m-2 text-center form-control rounded" type="text" id="i6" maxlength="6"/>
</div>
</div>
</form>
@ -43,9 +43,19 @@ function OTPInput() {
inputs[i].value = "";
}
let currIndex = 0;
function getCurrIndex() {
for(const [i, input] of inputs.entries()) {
if(input.value === "")
return i;
}
return 0;
}
document.addEventListener('keydown', (event) => {
let currIndex = getCurrIndex();
if (event.key === "Backspace") {
if (inputs[currIndex].value != "") {
inputs[currIndex].value = '';
@ -54,28 +64,41 @@ function OTPInput() {
inputs[currIndex - 1].focus();
currIndex--;
}
}
// Code has already been typed entirely
else if (currIndex === inputs.length - 1 && inputs[currIndex].value !== '')
{
event.preventDefault();
return;
}
});
function handleChange(index) {
const input = inputs[index];
// Remove non-numeric values from input
const correctValue = input.value.replace(/[^0-9]/g, "");
if (correctValue !== input.value)
input.value = correctValue;
if(correctValue.length == 0) {
input.focus();
return;
}
// Add new digit
else if ((event.keyCode >= 48 && event.keyCode <= 57)
|| (event.keyCode >= 96 && event.keyCode <= 105)){
inputs[currIndex].value = event.key;
if (currIndex < inputs.length - 1) {
inputs[currIndex + 1].focus();
currIndex++;
}
else
submitCode();
}
input.value = correctValue.substring(0, 1);
event.preventDefault();
});
if (index === 5) {
submitCode();
}
else {
inputs[index + 1].value = correctValue.substring(1) + inputs[index + 1].value;
handleChange(index + 1);
}
}
// Listen to event on all inputs
for (let i = 0; i < 6; i++) {
inputs[i].addEventListener("change", () => handleChange(i))
inputs[i].addEventListener("keyup", () => handleChange(i))
}
}
function submitCode() {