get intl-tel-input value with country code using jquery

11k Views Asked by At

I am trying to get value with the country code. https://www.jqueryscript.net/form/jQuery-International-Telephone-Input-With-Flags-Dial-Codes.html I am following this.

But I am not able to achieve the functionality of how to get the value with country code.

Suppose my input element is this.

<input type="phone_number" name="phone_no" value="" placeholder="Phone No" class="input form-control" autocomplete="off">

I did initialize the plugin

(async () => {
  let phoneNumberField = $('input[type=phone_number]');
  let isPhoneNumberFieldExist = phoneNumberField.length;
  if (isPhoneNumberFieldExist) {
    phoneNumberField.intlTelInput({
     
    });
  }
})();

Now while I am submitting the form I am receiving the above telephone number element too.

console.log(el); //will log the same above element 
console.log(el.value) // will log the number in input box

But I am not able to get value with the country code. I tried using instance variable like given in the linked guide. also tried using this

console.log( $(el).intlTelInput().getNumber());

But Nothing seems to work. Can any help me with how to get value with the country code?

2

There are 2 best solutions below

1
On

I think this is one way according to https://github.com/jackocnr/intl-tel-input

let phoneNumberField = $('input[type="phone_number]');
var iti = window.intlTelInputGlobals.getInstance(phoneNumberField);
console.log(iti.getNumber());
1
On

You can use intlTelInput('getSelectedCountryData').dialCode to get country code selected from dropdown.

Demo Code :

var instance = $("[name=phone_no]")
instance.intlTelInput();

$("[name=phone_no]").on("blur", function() {
  console.log($(this).val())
  console.log(instance.intlTelInput('getSelectedCountryData').dialCode) //get counrty code
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/css/intlTelInput.css" integrity="sha512-gxWow8Mo6q6pLa1XH/CcH8JyiSDEtiwJV78E+D+QP0EVasFs8wKXq16G8CLD4CJ2SnonHr4Lm/yY2fSI2+cbmw==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/intlTelInput-jquery.min.js" integrity="sha512-QK4ymL3xaaWUlgFpAuxY+6xax7QuxPB3Ii/99nykNP/PlK3NTQa/f/UbQQnWsM4h5yjQoMjWUhCJbYgWamtL6g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<input type="phone_number" name="phone_no" value="" placeholder="Phone No" class="input form-control" autocomplete="off">