Search code examples
javascriptstreet-address

Change Country for Loqate Address Verification Control


I'm successfully using the Loqate Address Verfication control, and filter its address results down to a single country, chosen in a select control.

However, when the country code in the select is changed, I've not been able to change the country filter in the Loqate address service to use the updated value.

var addressControl;
var avOptions = { suppressAutocomplete: false, setCountryByIP: false };

$(function () {
    addressControl = initialiseAddressValidation();
});

$("#CountryCode").change(function () {
            
    if (addressControl) {
        addressControl.destroy();
        addressControl = null;
    }            

    addressControl = initialiseAddressValidation();

});


function initialiseAddressValidation() {

    avOptions.key = $("#avKey").val();        
    avOptions.countries = { codesList: $("#CountryCode").val() };
    
    //other config truncated
    
}

Loqate's docs suggest that the .destroy() method I'm calling on change of the select should remove the control, and I tried setting it to null, before recreating it with the new country code value, but the address results it returns are still for the original country is was initialised with on load.

Does anyone know how to set a new country filter to the Loqate address verifier without completely reloading the page?


My working solution, based on @SlapdashFox 's invaluable assistance. Done this way to avoid having to completely re-create the control on every change of country

$("#CountryCode").change(function () {                
    if (addressControl) {
        addressControl.options.search.countries = $("#CountryCode").val();
    } else {
        addressControl = initialiseAddressValidation();
    }
});

Solution

  • Looks like you're changing the wrong value here, you want to be changing the search.countries attribute within your options object.

    In your above example you could do this as follows:

    function initialiseAddressValidation() {
        avOptions.key = $("#avKey").val();        
        avOptions.search = { countries: $("#CountryCode").val() };    
    }