How to get Country Code from (intl-tel-input) plugin after submitting the form?
Asked Answered
H

12

18

I've installed the plugin and Its displaying the countries correctly and working fine, but when I submit the form that has the input of type = "tel", the form does not submit the country code, I don't know how this works, but I did read all of instructions in https://github.com/jackocnr/intl-tel-input page, but I didn't understand how to get the full number + code country together so I can insert them into MySQL data base.

I'm so beginner, and just confused how to get this to work fine. Sorry if the question is not that hard, but I really don't know how this works.

The jQuery code I have:-

$("#telephone").intlTelInput({ 
    initialCountry: "sd",
    separateDialCode: true 
});
Hamulus answered 28/1, 2017 at 14:15 Comment(7)
Get familiar with your browsers javascript debugger (F12 normally). Then read the Documentation on github and play with it a bitMalcolm
When you get the number, put it in an <input> field in your form, maybe a hidden one if you like. Then it will get sent to the script when you submitMalcolm
Just went on to see the github demo and if the HTML produced for you is the same, then maybe something like $(".country[class*='active']").attr("data-dial-code") should give you the dial code for the country that's been selected. You'll have to pass that variable manually using submit then. Or append before the string the value obtained here to the telephone number being sent to PHP.Republicanize
@DhruvSaxena can you please teach me how to append the (data-dial-code) to the phone number input: <input type="tel" name="telephone" id="telephone" class="form-control" placeholder="Phone Number"> I used append jQuery function but its not working!Hamulus
Well, to be honest, this is just a quick fix that may not be very elegant or ideal. I don't how your form is being submitted, so can't really say much. However, what this does is: it appends the country code before the phone number value just as soon as the focus is taken away from the field: $("#telephone").on("blur", function(){ $(this).val("+" + $(".country[class*='active']").attr("data-dial-code") + $(this).val()); }); . If someone goes back to this field again and then leaves it (with or without editing), then it will once again cause the country code to be appended.Republicanize
Well, I guess that's okay, I fixed the issue of the value being append again by adding condition : if($(this).val() == '') { // code }Hamulus
Thank you very much for the very helpful information...Hamulus
F
16

intlTelInput option:

hiddenInput

Add a hidden input with the given name. Alternatively, if your input name contains square brackets (e.g. name="phone_number[main]") then it will give the hidden input the same name, replacing the contents of the brackets with the given name (e.g. if you init the plugin with hiddenInput: "full", then in this case the hidden input would have name="phone_number[full]"). On submit, it will automatically populate the hidden input with the full international number (using getNumber). This is a quick way for people using non-Ajax forms to get the full international number, even when nationalMode is enabled. Avoid this option when using Ajax forms and instead just call getNumber to get the full international number to send in the request. Note: requires the input to be inside a form element, as this feature works by listening for the submit event on the closest form element. Also note that since this uses getNumber internally, firstly it requires the utilsScript option, and secondly it expects a valid number and so should only be used after validation.

var phone_number = window.intlTelInput(document.querySelector("#phone_number"), {
  separateDialCode: true,
  preferredCountries:["in"],
  hiddenInput: "full",
  utilsScript: "//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.js"
});

$("form").submit(function() {
  var full_number = phone_number.getNumber(intlTelInputUtils.numberFormat.E164);
$("input[name='phone_number[full]'").val(full_number);
  alert(full_number)
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/css/intlTelInput.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/intlTelInput.min.js"></script>
<body>
  <form>
    <input type="tel" name="phone_number[main]" id="phone_number" />
    <button type="submit" name="save">Save</button>
  </form>

</body>

Php Code

You can get full number like

$phone_number = $_REQUEST['phone_number']['full'];
Flunk answered 9/7, 2020 at 12:17 Comment(3)
var full_number = $(".iti__selected-dial-code").text(); alert(full_number)Perdomo
You must need to use utils.js script then you will get full number "//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.js"Flunk
shouldnt $phone_number = $_REQUEST['full']; without ['phone_number'] be enough? - just askingFlatt
R
3
<form method="post">
    <input type="hidden"  id="code" name ="code" value="1" >
    <input type="text" id="phone" name ="phone" value="" >
    <button type="submit" >Send Verification Text</button>
</form>
<script type="text/javascript">
    $(document).ready(function () {
        $("#phone").intlTelInput({
            preferredCountries: ["us", "ca"],
            separateDialCode: true,
            initialCountry: ""
        }).on('countrychange', function (e, countryData) {
            $("#code").val(($("#phone").intlTelInput("getSelectedCountryData").dialCode));

        });


    });
</script>
Rigel answered 8/12, 2019 at 7:15 Comment(0)
E
3

They have a function already. This will return something like this.

phoneInput.getSelectedCountryData();

{ name: "Afghanistan (‫افغانستان‬‎)", iso2: "af", dialCode: "93" }

Elan answered 1/4, 2022 at 21:16 Comment(1)
perfect, it works 😄 phoneInput.getSelectedCountryData()['dialCode']Erikaerikson
L
2

Submit the form with this:

HTML:

<form action="post">
  <div class="select">
    <input type="hidden" id="phone2" name="phone"/>
    <input type="tel" id="phone" name="phone-full">
  </div>
</form>

JAVASCRIPT:

$("form").submit(function() {
    $("#phone2").val($("#phone").intlTelInput("getNumber"));
});
Lineman answered 10/8, 2017 at 16:39 Comment(0)
E
2

Searching a bit in the link you posted I found a nice example doing what you're asking

Taking some inspiration from the example, here is the code

HTML

<form action="post">
  <div class="select">
    <input type="hidden" id="country" name="country"/>
    <input type="tel" id="phone" name="phone">
  </div>
</form>

JS

var input = $('#phone');
var country = $('#country');
var iti = intlTelInput(input.get(0))

// listen to the telephone input for changes
input.on('countrychange', function(e) {
  // change the hidden input value to the selected country code
  country.val(iti.getSelectedCountryData().iso2);
});
Entero answered 1/7, 2019 at 18:6 Comment(1)
this like worked for me instead of country.val(iti.getSelectedCountryData().iso2); I used $("#code").val(($("#phone").intlTelInput("getSelectedCountryData").dialCode));Bordure
P
0

// Add code in intlTelInput.js to use current location show code

$currentCountry = 'us';
    $.ajax({
        url: 'http://ip-api.com/json/',
        async: false,
        success:function(data){
            $currentCountry = data.countryCode.toLowerCase();
            // console.log(data.countryCode.toLowerCase());
        }
    })

    $selected = $('.country_code').attr('country_iso_code2') != undefined ? $('.country_code').attr('country_iso_code2') : $currentCountry;
    // console.log($selected);
    var pluginName = "intlTelInput", defaults = {
        preferredCountries: [ $selected ],
        // united states and united kingdom
        initialDialCode: true,
        americaMode: false,
        onlyCountries: []
    };
Pooley answered 15/5, 2019 at 13:0 Comment(0)
K
0

HTML

(ng2TelOutput)="getNumberCellNo1($event)" 

Javascript

getNumberCellNo1(e:any)
  {
    this.cell_code1.setNumber(e) 
    this.cellnumber1=e
  }

The getNumber() will give you the country code and number as +919843133490. The setNumber will set the country flag and place the number inn input field.

Hope it helped. Any further queries can be asked.

Keslie answered 4/2, 2020 at 18:6 Comment(0)
T
0

HTML CODE Use this html code

<input type="text" name="ccode" id="ccode">
<input type="tel" id="phone" name="phone" >

JAVA SCRIPT CODE

 //Country code

var titilec=title.split(":");
document.getElementById('ccode').value=titilec[1];

Add the above js code in your intlTelInput.js file after the below code

// update the selected country's title attribute

var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown";
  this.selectedFlag.setAttribute("title", title);
Trainee answered 5/8, 2021 at 14:29 Comment(0)
L
0

HTML

<input type="tel" name="phone" class="phone-inteltel" required>

Javascript

 var input = document.querySelector(".phone-inteltel");
 window.intlTelInput(input, {
   separateDialCode: true,
   initialCountry: "auto",
   hiddenInput: "phone",
   geoIpLookup: function (callback) {
     $.get('https://ipinfo.io', function () { }, "jsonp").always(function (resp) {
       var countryCode = (resp && resp.country) ? resp.country : "tr";
       callback(countryCode);
     });
   },
   utilsScript: "https://intl-tel-input.com/node_modules/intl-tel-input/build/js/utils.js?1638200991544" // just for formatting/placeholders etc
 }); 
Lipophilic answered 15/11, 2022 at 10:51 Comment(0)
P
0

This is one liner to access the full number.

`+${$("#mobileno").intlTelInput("getSelectedCountryData").dialCode} ${$("#mobileno").val()}`;
Prostatectomy answered 24/10, 2023 at 9:15 Comment(0)
K
0
$(document).on("click","ul .iti__country", function(){
    var ss =  $(".iti--separate-dial-code .iti__selected-flag ").attr( "title" );
  alert(ss);
});
Kettle answered 6/7, 2024 at 13:37 Comment(1)
Thank you for posting this answer. While this code may answer the question, might you please edit your post to add an explanation as to why/how it works? This can help future readers learn and apply your answer. You are also more likely to get positive feedback (upvotes) when you include an explanation.Munt
P
-1

For getting country short code and dial code add below lines(hidden inputs) inside the <form>,

<input type="hidden" name="dialCode" id="dialCode">
<input type="hidden" name="countryCode" id="countryCode">

Add below javascript code

$('.iti__country-list li').click(function(){
  $("#dialCode").val($(this).data('dial-code'));
  $("#countryCode").val($(this).data('country-code-code'));
})

Here, you are getting dial code and country short code string in the hidden inputs when the code is selected from the dropdown.

And after the form submitting, concatenate the dial code and mobile number to save in the database.

Platysma answered 1/3, 2022 at 7:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.