Reputation:
I need to add country code in mobile number input field prefix. I have tried the below code.
<script>
var telInput = $("#mobile"),
errorMsg = $("#error-msg"),
validMsg = $("#valid-msg");
// initialise plugin
telInput.intlTelInput({
allowExtensions: true,
formatOnDisplay: true,
autoFormat: true,
autoHideDialCode: true,
autoPlaceholder: true,
defaultCountry: "in",
ipinfoToken: "yolo",
nationalMode: false,
numberType: "MOBILE",
//onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
preferredCountries: ['sa', 'ae', 'qa','om','bh','kw','ma'],
preventInvalidNumbers: true,
separateDialCode: false,
initialCountry: "in",
geoIpLookup: function(callback) {
$.get("http://ipinfo.io", function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
callback(countryCode);
});
},
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.9/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");
} else {
telInput.addClass("error");
errorMsg.removeClass("hide");
}
}
});
// on keyup / change flag: reset
telInput.on("keyup change", reset);
</script>
I have tried and it is working. But I can submit mobile number without country code, and that should not be. The country code should not be editable.
I have used below js and css:
<link href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.9/css/intlTelInput.css" rel="stylesheet" media="screen">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.9/js/intlTelInput.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.9/js/intlTelInput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.9/js/utils.js"></script>
Upvotes: 0
Views: 42130
Reputation: 144
There is a better and more flexible way to collect telephone numbers, in the form of an excellent jQuery plugin
You can also play with a live demo here
Usage is simple make sure you’ve included jQuery, the library, and the CSS file, and that the flag sprite is available and properly referenced from the CSS – you’ll find it in build/img/flags.png
Next, create an element:
<input type="tel" id="number">
Finally, intialize it as follows:
$("#number").intlTelInput();
For a full list of configuration options, consult the documentation.
Upvotes: 4