verification.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334
  1. const inputElements = [...document.querySelectorAll("input.code-input")];
  2. (function () {
  3. inputElements.forEach((ele, index) => {
  4. ele.addEventListener("keydown", (e) => {
  5. // if the keycode is backspace & the current field is empty
  6. // focus the input before the current. Then the event happens
  7. // which will clear the "before" input box.
  8. if (e.keyCode === 8 && e.target.value === "")
  9. inputElements[Math.max(0, index - 1)].focus();
  10. });
  11. ele.addEventListener("input", (e) => {
  12. // take the first character of the input
  13. // this actually breaks if you input an emoji like 👨‍👩‍👧‍👦....
  14. // but I'm willing to overlook insane security code practices.
  15. const [first, ...rest] = e.target.value;
  16. e.target.value = first ?? ""; // first will be undefined when backspace was entered, so set the input to ""
  17. const lastInputBox = index === inputElements.length - 1;
  18. const didInsertContent = first !== undefined;
  19. if (didInsertContent && !lastInputBox) {
  20. // continue to input the rest of the string
  21. inputElements[index + 1].focus();
  22. inputElements[index + 1].value = rest.join("");
  23. inputElements[index + 1].dispatchEvent(new Event("input"));
  24. }
  25. });
  26. });
  27. // mini example on how to pull the data on submit of the form
  28. function onSubmit(e) {
  29. e.preventDefault();
  30. const code = inputElements.map(({ value }) => value).join("");
  31. console.log(code);
  32. }
  33. })();