I have a Javascript function that auto-populates form fields based on an available list of addresses. If a User selects an option that is a country other than the US, we are not going to require Zip Code / State fields in our form that gets populated (all "required" validation is handled through "data-required=true"). The form is dynamically generated, so I cannot use the .change() method that some people are suggesting.
I have a "Change" listener setup to remove the "data-required" attribute, which works if they click the Country dropdown and select a different country. However, it does not work when the Javascript function changes that same dropdown.
jQuery( document ).ready(function() {
jQuery('body').on('change','#coHCOUN',function() {
if(jQuery(this).val() == 'US') {
jQuery('#coHPOST').attr('data-required','true');
jQuery('#coHSTE').attr('data-required','true');
} else {
jQuery('#coHPOST').removeAttr('data-required');
jQuery('#coHSTE').removeAttr('data-required');
}
});
});
The function that grabs hidden form values when selecting an address, and applies them to the form. This is older code written in vanilla javascript, not jQuery:
function SetShipTo(CIPID) {
document.getElementById("coHNAME").value=document.getElementById("vSHIPTO" + CIPID + "HNAME").value;
document.getElementById("coHATN").value=document.getElementById("vSHIPTO" + CIPID + "HATN").value;
document.getElementById("coHAD1").value=document.getElementById("vSHIPTO" + CIPID + "HAD1").value;
document.getElementById("coHAD2").value=document.getElementById("vSHIPTO" + CIPID + "HAD2").value;
document.getElementById("coHAD3").value=document.getElementById("vSHIPTO" + CIPID + "HAD3").value;
document.getElementById("coHSTE").value=document.getElementById("vSHIPTO" + CIPID + "HSTE").value;
document.getElementById("coHPOST").value=document.getElementById("vSHIPTO" + CIPID + "HPOST").value;
document.getElementById("coHCOUN").value=document.getElementById("vSHIPTO" + CIPID + "HCOUN").value;
document.getElementById("coHVIA").value=document.getElementById("vSHIPTO" + CIPID + "HVIA").value;
document.getElementById("coHSHPR").value=document.getElementById("vSHIPTO" + CIPID + "HSHPR").value;
document.getElementById("coCIPLOC").value=document.getElementById("vSHIPTO" + CIPID + "CIPLOC").value;
document.getElementById("SAVESHIPTOFU").checked=false;
}
Is there another event listener I can add to detect if a value changes from a javascript function? I do not want to add extra code to the auto-populate function if possible