How to put phone country code in intlTelInput in brackets
Depending on the form of the documentation here - https://github.com/jackocnr/intl-tel-input - you will need something like this:
var intlNumber = $("#phone").intlTelInput("getNumber"); // get full number eg +17024181234
var countryData = $("#phone").intlTelInput("getSelectedCountryData"); // get country data as obj
var countryCode = countryData.dialCode; // using updated doc, code has been replaced with dialCode
countryCode = "+" + countryCode; // convert 1 to +1
var newNo = intlNumber.replace(countryCode, "(" + coountryCode+ ")" ); // final version
source to share
Just use this code to get the country code from your phone number:
you can use var getCode = telInput.intlTelInput('getSelectedCountryData').dialCode;
Here's a demo: https://output.jsbin.com/cuvoqagotu
https://jsbin.com/cuvoqagotu/edit?html,css,js
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/6.4.1/css/intlTelInput.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/6.4.1/js/intlTelInput.min.js"></script>
<style>
.hide {
display: none;
}
</style>
</head>
<body>
<input id="phone" type="tel">
<span id="valid-msg" class="hide">? Valid</span>
<span id="error-msg" class="hide">Invalid number</span>
</body>
</html>
JS:
var telInput = $("#phone"),
errorMsg = $("#error-msg"),
validMsg = $("#valid-msg");
// initialise plugin
telInput.intlTelInput({
utilsScript:"https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.4/js/utils.js"
});
var reset = function() {
telInput.removeClass("error");
errorMsg.addClass("hide");
validMsg.addClass("hide");
};
// on blur: validate
telInput.blur(function() {
reset();
if ($.trim(telInput.val())) {
if (telInput.intlTelInput("isValidNumber")) {
validMsg.removeClass("hide");
/* get code here*/
var getCode = telInput.intlTelInput('getSelectedCountryData').dialCode;
alert(getCode);
} else {
telInput.addClass("error");
errorMsg.removeClass("hide");
}
}
});
// on keyup / change flag: reset
telInput.on("keyup change", reset);
source to share
You don't add the dialing country code directly to the input, you just attach it when the user submits the form or saves it in another hidden input and validates it on your server side:
You can also display it to users so they know they don't need to type it as they type:
https://intl-tel-input.com/node_modules/intl-tel-input/examples/gen/national-mode.html
source to share