Advertisement
nicolaslagios

Convert text field to phone field - JS

Jul 31st, 2023
2,053
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.10 KB | Source Code | 0 0
  1.     const inputField = document.querySelector("#ff_4_input_text");
  2.     inputField.addEventListener("keydown", function (event) {
  3.       if (
  4.         event.key === "Backspace" ||
  5.         event.key === "Delete" ||
  6.         event.key === "ArrowLeft" ||
  7.         event.key === "ArrowRight" ||
  8.         event.key === "ArrowUp" ||
  9.         event.key === "ArrowDown" ||
  10.         event.key === "Tab" ||
  11.         (event.key.startsWith("Num") && event.key.length > 3)
  12.       ) {
  13.         return;
  14.       }
  15.       if (/^\d$/.test(event.key)) {
  16.         const currentValue = event.target.value;
  17.         if (!currentValue.startsWith("+30")) {
  18.           event.target.value = "+30" + currentValue;
  19.         }
  20.       } else {
  21.         event.preventDefault();
  22.       }
  23.     });
  24.  
  25.     inputField.addEventListener("paste", function (event) {
  26.       const pastedText = (event.clipboardData || window.clipboardData).getData("text");
  27.       if (!/^\d*$/.test(pastedText)) {
  28.         event.preventDefault();
  29.       } else {
  30.         const currentValue = event.target.value;
  31.         event.target.value = "+30" + currentValue;
  32.       }
  33.     });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement