diff --git a/templates/login/otp_input.html b/templates/login/otp_input.html index cf8dcfe..2b67e43 100644 --- a/templates/login/otp_input.html +++ b/templates/login/otp_input.html @@ -37,77 +37,53 @@ function OTPInput() { // Set form destination document.getElementById("totp_form").action = location.href; - const inputs = document.querySelectorAll('#otp > *[id]'); + const inputs = [...document.querySelectorAll('#otp > *[id]')]; for (let i = 0; i < inputs.length; i++) { // Reset form on init inputs[i].value = ""; } - - function getCurrIndex() { - for(const [i, input] of inputs.entries()) { - if(input.value === "") - return i; - } - - return 0; + function getMergedCode() { + return inputs.map((i) => i.value).join("") } + function submitCode() { + const code = getMergedCode(); + + document.getElementById("code").value = code; + document.getElementById("totp_form").submit(); + } document.addEventListener('keydown', (event) => { - let currIndex = getCurrIndex(); - if (event.key === "Backspace") { - if (inputs[currIndex].value != "") { - inputs[currIndex].value = ''; - } else if (currIndex > 0) { - inputs[currIndex - 1].value = ""; - inputs[currIndex - 1].focus(); - currIndex--; - } - - event.preventDefault(); - return; - } + let currCode = getMergedCode(); + if (event.key === "Backspace" && currCode.length > 0) { + inputs[currCode.length - 1].value = ""; + inputs[currCode.length - 1].focus(); + } }); - function handleChange(index) { - const input = inputs[index]; - + function handleChange() { // 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; + const fullCode = getMergedCode().replace(/[^0-9]/g, "").substring(0, 6); + + for (let i = 0; i < 6; i++) { + inputs[i].value = i <= fullCode.length ? fullCode.substring(i, i + 1) : ""; } - input.value = correctValue.substring(0, 1); - - if (index === 5) { + if (fullCode.length === 6) { submitCode(); } else { - inputs[index + 1].value = correctValue.substring(1) + inputs[index + 1].value; - handleChange(index + 1); + inputs[fullCode.length].focus() } } // 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)) + inputs[i].addEventListener("change", () => handleChange()) + inputs[i].addEventListener("keyup", () => handleChange()) } -} -function submitCode() { - const code = [...document.querySelectorAll('#otp > *[id]')] - .map((i) => i.value) - .join(""); - - document.getElementById("code").value = code; - document.getElementById("totp_form").submit(); } document.addEventListener("DOMContentLoaded", () => OTPInput());