2

I'm new on javascript. I want to create form with two fields: phone number and country. I want to separate them on my database. How can i get country value from intl-tel-input?

For example:

<form>
    <label>Phone Number</label>
    <!-- using intl-tel-input -->
    <input type="tel" name="phone">

    <label>Country</label>
    <!-- how can i get country value automatically here from phone number field? -->
    <input type="text" name="country">
</form>

Anyone can help me figure this out? thanks in advance.

LucileDT
  • 546
  • 1
  • 6
  • 22
Abhista R
  • 45
  • 1
  • 5

1 Answers1

1

<!-- REQUIRED CDN  -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.min.css"
crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js" crossorigin="anonymous"></script>

<input name="phone" type="text" class="form-control mb-2 inptFielsd" id="phone"
placeholder="Phone Number" />

<label>Country</label>
<input id="country" type="text" name="country">

<script>
    var input = document.querySelector("#phone");
    window.intlTelInput(input, {
        separateDialCode: true,
        customPlaceholder: function (
            selectedCountryPlaceholder,
            selectedCountryData
        ) {
            return "e.g. " + selectedCountryPlaceholder;
        },
    });
  
    var iti = window.intlTelInputGlobals.getInstance(input);

    input.addEventListener('input', function() { 
      var countryName = iti.getSelectedCountryData().name;
      document.getElementById('country').value = countryName;
    });
</script>
Yalcin Kilic
  • 778
  • 3
  • 14
  • do you have any idea how to get phone number with country dial code? i try your code but the phone number wont show the country dial code – Abhista R Dec 08 '21 at 07:51
  • Just use this to get full phone number with country code // var full_number = iti.getNumber(); – Ankush Rathour Jul 06 '22 at 13:06