i have 2 codes one is old and it was working perfectly then I decided to upgrade to jquery 3.6.0 but I faced a problem that the code stopped to work so i got a new code from here but its not working properly.
the old code
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");
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);
<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>
<input id="phone" type="tel">
<span id="valid-msg" class="hide">✓ Valid</span>
<span id="error-msg" class="hide">Invalid number</span>
on jsbin : https://jsbin.com/heqokumase/edit?html,js,output
this code is working perfectly for example it doesn't allow any input except (numbers and +) also it removes the country code automatically if user type it with the number.
the new code
var input = document.querySelector("#registration-phone-number");
var errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];
window.addEventListener("load", function() {
errorMsg = document.querySelector("#error-msg"),
validMsg = document.querySelector("#valid-msg");
var iti = window.intlTelInput(input, {
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/utils.js"
});
window.intlTelInput(input, {
// allowDropdown: false,
// autoHideDialCode: false,
// autoPlaceholder: "off",
// dropdownContainer: document.body,
// excludeCountries: ["us"],
// formatOnDisplay: false,
geoIpLookup: function(callback) {
$.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
callback(countryCode);
});
},
hiddenInput: "full_number",
initialCountry: "auto",
// localizedCountries: { 'de': 'Deutschland' },
// nationalMode: false,
// onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
placeholderNumberType: "MOBILE",
// preferredCountries: ['cn', 'jp'],
separateDialCode: true,
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/utils.js",
});
$(validMsg).hide();
input.addEventListener('blur', function() {
reset();
if (input.value.trim()) {
if (iti.isValidNumber()) {
$(validMsg).show();
} else {
$(input).addClass('form-control-danger');
var errorCode = iti.getValidationError();
errorMsg.innerHTML = errorMap[errorCode];
$(errorMsg).show();
}
}
});
input.addEventListener('change', reset);
input.addEventListener('keyup', reset);
});
var reset = function() {
$(input).removeClass('form-control-danger');
errorMsg.innerHTML = "";
$(errorMsg).hide();
$(validMsg).hide();
};
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/css/intlTelInput.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/intlTelInput.js"></script>
<input id="registration-phone-number" type="tel">
<span id="valid-msg" class="hide">✓ Valid</span>
<span id="error-msg" class="hide">Invalid number</span>
on jsbin : https://jsbin.com/mumedakiku/edit?html,js,output
it works but it doesn't restrict the input to only (numbers and +) also it doesn't remove the country code automatically on number input also if you enter the number without typing the country code it gives the error "too short" especially at the beginning on load it getts the user country automatically but as I said if you write the number without the country code it gives error "too short" unless you select the country again then it will give valid.
how to make the new code work perfect like the old one with the new update of jquery and the new update of intl-tel-input?
i solved it and here is the code for anyone who wants it :)
var input = document.querySelector("#phone"),
errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"],
result = document.querySelector("#result");
window.addEventListener("load", function () {
errorMsg = document.querySelector("#error-msg");
function getIp(callback) {
fetch('https://ipinfo.io', { headers: { 'Accept': 'application/json' }})
.then((resp) => resp.json())
.catch(() => {
return {
country: '',
};
})
.then((resp) => callback(resp.country));
}
var iti = window.intlTelInput(input, {
// allowDropdown: false,
// dropdownContainer: document.body,
// excludeCountries: ["us"],
hiddenInput: "full_number",
nationalMode: false,
formatOnDisplay: true,
separateDialCode: true,
autoHideDialCode: true,
autoPlaceholder: "aggressive" ,
initialCountry: "auto",
placeholderNumberType: "MOBILE",
preferredCountries: ['il','ge'],
geoIpLookup: getIp,
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/utils.js",
});
input.addEventListener('keyup', formatIntlTelInput);
input.addEventListener('change', formatIntlTelInput);
function formatIntlTelInput() {
if (typeof intlTelInputUtils !== 'undefined') { // utils are lazy loaded, so must check
var currentText = iti.getNumber(intlTelInputUtils.numberFormat.E164);
if (typeof currentText === 'string') { // sometimes the currentText is an object :)
iti.setNumber(currentText); // will autoformat because of formatOnDisplay=true
}
}
}
input.addEventListener('keyup', function () {
reset();
if (input.value.trim()) {
if (iti.isValidNumber()) {
$(input).addClass('form-control is-valid');
} else {
$(input).addClass('form-control is-invalid');
var errorCode = iti.getValidationError();
errorMsg.innerHTML = errorMap[errorCode];
$(errorMsg).show();
}
}
});
input.addEventListener('change', reset);
input.addEventListener('keyup', reset);
var reset = function () {
$(input).removeClass('form-control is-invalid');
errorMsg.innerHTML = "";
$(errorMsg).hide();
};
////////////// testing - start //////////////
input.addEventListener('keyup', function(e) {
e.preventDefault();
var num = iti.getNumber(),
valid = iti.isValidNumber();
result.textContent = "Number: " + num + ", valid: " + valid;
}, false);
input.addEventListener("focus", function() {
result.textContent = "";
}, false);
$(input).on("focusout", function(e, countryData) {
var intlNumber = iti.getNumber();
console.log(intlNumber);
});
////////////// testing - end //////////////
});
//-----------------------only-phone-number-input code (with +)-------------------------------start-------//
function isPhoneNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode != 43 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
//-----------------------only-phone-number-input code (with +)-------------------------------end-------//
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/css/intlTelInput.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/intlTelInput.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
<div class="form-group has-danger">
<input id="phone" class="" type="tel" name="phone" maxlength="15" />
<br>
<span id="error-msg" class="hide"></span>
<p id="result"></p>
</div>