This script enhances phone input fields with auto-detected country codes, using the intl-tel-input library. It prevents users from modifying or deleting the country code, ensures consistent formatting, and supports dynamic country selection. GeoIP lookup sets the initial country code based on the user's location. Inspired by
Julian Galluzzo
Use this in the code
View now
{"content":[{"id":"gqftio","name":"container","parent":"joaxnz","children":["ddkupy","lgtrme"],"settings":{}},{"id":"ddkupy","name":"form","parent":"gqftio","children":[],"settings":{"fields":[{"type":"tel","label":"Phone","id":"e69562","name":"phone","maxLength":"17","required":true}],"submitButtonStyle":"primary","actions":["email"],"successMessage":"Message successfully sent. We will get back to you as soon as possible.","emailSubject":"Contact form request","emailTo":"admin_email","fromName":"PostPilot","emailErrorMessage":"Submission failed. Please reload the page and try to submit the form again.","htmlEmail":true,"mailchimpPendingMessage":"Please check your email to confirm your subscription.","mailchimpErrorMessage":"Sorry, but we could not subscribe you.","sendgridErrorMessage":"Sorry, but we could not subscribe you.","_margin":{"left":"auto","right":"auto"},"submitButtonWidth":"100%","submitButtonBackgroundColor":{"hex":"#6ab1f3","id":"vqhiae","name":"Color #1"},"submitButtonTypography":{"color":{"hex":"#ffffff","id":"edddcc","name":"Color #2"}},"submitButtonBorder":{"radius":{"top":"10","right":"10","bottom":"10","left":"10"}},"fieldMargin":{"bottom":"10"},"fieldBorder":{"radius":{"top":"10","right":"10","bottom":"10","left":"10"}},"emailContent":"{{all_fields}}","_width":"40%","_width:mobile_landscape":"100%"},"themeStyles":{}},{"id":"lgtrme","name":"code","parent":"gqftio","children":[],"settings":{"signature":"95551922ba9ade8b065c0a870b544572","user_id":4,"time":1747475847,"parseDynamicData":true,"noRoot":true,"executeCode":true,"code":"\n\n\n\n\n\n\n\n\n","javascriptCode":"document.addEventListener(\"DOMContentLoaded\", function () {\n const phoneInputField = document.querySelector('input[name=\"phone\"]');\n if (!phoneInputField) return;\n\n const phoneInput = window.intlTelInput(phoneInputField, {\n initialCountry: \"auto\",\n geoIpLookup: function (callback) {\n fetch(\"https://ipapi.co/json/ \")\n .then((res) => res.json())\n .then((data) => callback(data.country_code || \"us\"))\n .catch(() => callback(\"us\"));\n },\n utilsScript: \"https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js \",\n showSelectedDialCode: true,\n dropdownContainer: document.body,\n });\n\n function applyInputMask() {\n const placeholder = phoneInputField.getAttribute(\"placeholder\") || \"\";\n const selectedCountryData = phoneInput.getSelectedCountryData();\n const dialCode = selectedCountryData?.dialCode ? `+${selectedCountryData.dialCode}` : \"\";\n const digitCount = placeholder.replace(/[^0-9]/g, \"\").length;\n const dynamicMask = dialCode + \" \" + \"9\".repeat(digitCount);\n const formattedMask = dialCode + \" \" + placeholder.replace(/[0-9]/g, \"9\").replace(/[^0-9()\\s\\-]/g, \"\");\n\n $(phoneInputField).inputmask({\n mask: [dynamicMask, formattedMask],\n jitMasking: true,\n placeholder: \"\",\n showMaskOnHover: false,\n showMaskOnFocus: false,\n clearIncomplete: true,\n keepStatic: true,\n });\n }\n\n function setInitialDialCode() {\n const currentVal = phoneInputField.value.trim();\n // Only reset if input is empty or contains only the dial code\n if (!currentVal || /^\\+\\d+$/.test(currentVal)) {\n phoneInput.setNumber(\"\"); // Clear to avoid duplicate dial code\n }\n }\n\n // Initial setup\n applyInputMask();\n setInitialDialCode();\n\n // On country change\n phoneInputField.addEventListener(\"countrychange\", function () {\n $(phoneInputField).inputmask(\"remove\");\n applyInputMask();\n setInitialDialCode();\n });\n\n // Form handling for hidden full number\n const form = phoneInputField.closest(\"form\");\n if (form) {\n let hiddenInput = form.querySelector('input[name=\"phone_full\"]');\n if (!hiddenInput) {\n hiddenInput = document.createElement(\"input\");\n hiddenInput.type = \"hidden\";\n hiddenInput.name = \"phone_full\";\n form.appendChild(hiddenInput);\n }\n\n form.addEventListener(\"submit\", () => {\n const phoneNumber = phoneInput.getNumber();\n hiddenInput.value = phoneNumber;\n console.log(\"Full Phone Number:\", phoneNumber);\n });\n }\n\n // Modify country list: show country name and dial code\n const observer = new MutationObserver(() => {\n const countryItems = document.querySelectorAll(\".iti__country-list .iti__country\");\n countryItems.forEach((item) => {\n const dialCode = item.getAttribute(\"data-dial-code\");\n const nameSpan = item.querySelector(\".iti__country-name\");\n if (nameSpan && !nameSpan.textContent.includes(`(+${dialCode})`)) {\n nameSpan.textContent = `${nameSpan.textContent} (+${dialCode})`;\n }\n });\n });\n\n observer.observe(document.body, { childList: true, subtree: true });\n});"},"themeStyles":{}}],"source":"bricksCopiedElements","sourceUrl":"https://nsourc.com","version":"1.12.3","globalClasses":[],"globalElements":[]}