I have multiple forms on a single page, each containing a phone number field driven by a JavaScript plugin.
As a result, I am faced with having to properly initialize a large number of these fields. Manually initializing them would require:
number of forms * number of phone input fields = number of initializations
Currently, only the first field is functioning correctly while the rest remain uninitialized.
The markup structure is as follows:
<input type="tel" class="phone_flag" name="phone_tab1[main]" required="">
<input type="tel" class="phone_flag" name="phone_tab2[main]" required="">
<input type="tel" class="phone_flag" name="phone_tab3[main]" required="">
xxx
...
I received advice suggesting that in order to make it work properly, I should use querySelectorAll
with a forEach
loop. Then, I need to call the PhoneDisplay
function and pass in the element itself instead of the class name. Finally, initialize the plugin on that specific element directly.
While I have implemented this solution, it only successfully initializes the first element.
JavaScript initialization code:
document.querySelectorAll('.phone_flag').forEach(el => {
PhoneDisplay(el.className);
});
function PhoneDisplay(ClassName){
var input = document.querySelector('.' + `${ClassName}`);
var iti = window.intlTelInput(input, {
hiddenInput: "full",
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('proxy.php', function() {}).always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
callback(countryCode);
});
},
hiddenInput: "full_phone",
utilsScript: "intlTelInput/js/utils.js"
});
var reset = function() {
input.classList.remove("error");
errorMsg.innerHTML = "";
errorMsg.classList.add("hide");
validMsg.classList.add("hide");
};
input.addEventListener('blur', function() {
reset();
if (input.value.trim()) {
if (iti.isValidNumber()) {
validMsg.classList.remove("hide");
} else {
input.classList.add("error");
var errorCode = iti.getValidationError();
errorMsg.innerHTML = errorMap[errorCode];
errorMsg.classList.remove("hide");
}
}
});
input.addEventListener('change', reset);
input.addEventListener('keyup', reset);
}