diff --git a/templates/login/otp_input.html b/templates/login/otp_input.html index 27c9ba3..cf8dcfe 100644 --- a/templates/login/otp_input.html +++ b/templates/login/otp_input.html @@ -15,12 +15,12 @@
- - - - - - + + + + + +
@@ -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; } + + input.value = correctValue.substring(0, 1); - // 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(); + if (index === 5) { + submitCode(); } + else { + inputs[index + 1].value = correctValue.substring(1) + inputs[index + 1].value; + handleChange(index + 1); + } + } - event.preventDefault(); - }); + // 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() {