International phone number input in HTML and JavaScript

PHOTO EMBED

Sun Jun 26 2022 09:19:46 GMT+0000 (UTC)

Saved by @edsonjorgef1 #blade #javascript #html

<html>
</head>
    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"
      />

<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>

   <script>
    const phoneInputField = document.querySelector("#phone");
    const phoneInput = window.intlTelInput(phoneInputField, {
        // preferredCountries: ["us", "mz", "sa", "za"],
        // initialCountry: "auto",
        // geoIpLookup: getIp,
        utilsScript:
        "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
    });

    const info = document.querySelector(".alert-info");

    function process(event) {
    event.preventDefault();
      
    const phoneNumber = phoneInput.getNumber();

    info.style.display = "";
    info.innerHTML = `Phone number in E.164 format: <strong>${phoneNumber}</strong>`;
    }

    function getIp(callback) {
     fetch('https://ipinfo.io/json?token=<your token>', { headers: { 'Accept': 'application/json' }})
       .then((resp) => resp.json())
       .catch(() => {
         return {
           country: 'us',
         };
       })
       .then((resp) => callback(resp.country));
    }
 </script>

</head>

 <body>
    <div class="container">
        <form id="login" onsubmit="process(event)">
          <p>Enter your phone number:</p>
          <input id="phone" type="tel" name="phone" />
          <input type="submit" class="btn" value="Verify" />
        </form>
        <div class="alert alert-info" style="display: none;"></div>
    </div>
 </body>
 </html>
content_copyCOPY