javascriptjquerylibphonenumberintl-tel-input

International Telephone Input number formatting way around?


As I understand they have removed the autoformat option on the latest International Telephone Input library.This option formatted the number accordingly to the country the user choose. But according to the forms, i can still use util.js and format-number function to achieve this options (https://github.com/jackocnr/intl-tel-input/wiki/utils.js) I tried multiple times but not being able to apply this option. For example for US Number, how would I format the number to this ex:(201)-255-6655. This is my code below. As I see this seems to be the best js library for international numbers.

$( document ).ready(function() {

    $('#contactForm')
    .find('[name="phoneNumber"]')
        .intlTelInput({
            utilsScript:"https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/js/utils.js",
          
            autoPlaceholder: true,
            initialCountry:"us",
            geoIpLookup:"auto",

        });


    });
<!DOCTYPE html>
<html>
<head>
<title>Phone</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/css/intlTelInput.css">
<link rel="stylesheet" href="./intlmask.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/js/intlTelInput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/js/utils.js"></script>

<script src="./intlmask.js"></script>
</head>
<body>

  <form id="contactForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Phone number</label>
        <div class="col-xs-5">
            <input type="tel" class="form-control" name="phoneNumber" />
        </div>
    </div>
</form>

</body>
</html>

like this enter image description here


Solution

  • so I basically added a function and ran it when user-focused out of the input. utils.js already provide us with formatting (intlTelInputUtils.formatNumber). we just have to pass the number and country code/initial to it. check my code below

        function test(){
            var number =  $('input[name="phoneNumber"]').val();
            var classf = $(".selected-flag > div").attr("class");
            var flag = classf.slice(-2);
      
            console.log("check number: ", number);
            console.log("check classf: ", classf);
            console.log("check flag: ", flag);
            
            var formattedNumber = intlTelInputUtils.formatNumber(number, flag, intlTelInputUtils.numberFormat.INTERNATIONAL);
            $('input[name="phoneNumber"]').val(formattedNumber);
    
    }