I have a Wordpress gravity form plugin that uses Google Address API to automatically populate address fields such as city, state, zip and country.
I have written a jQuery script that grabs the country and state and auto-populate those fields with the value and made State to be readonly.
Similarly if the user tries to change the country, the script will set back the value to the original one.
I want State to remain unchanged (readonly), the user can’t change it since it is readonly BUT the autocomplete script can change it after the user change the address using autocomplete.
The jQuery trigger() should capture the change event done programmatically, I have written the script below but the autocomplete can still change the State.
$("#input_54_3_4").trigger("change");
$("#input_54_3_4").on('change', function(){
console.log("Inside change")
if ($("#input_54_3_4").val() != $("#input_54_1").val()){
$("#input_54_3_4").val(provSelected);
console.log("Inside if");
alert("Only " + provSelected +" addresses are allowed in this address field");
$(".address_line_2 > input, .address_city > input, .address_zip >input").val("");
}
});
Thank you for that. It’s likely to be 24 hours before I return, but your assistance has made it much more likely that someone else here will be able to assist in the interim.
First, declare a currentState variable in the the place_changed event:
google.maps.event.addListener(autocomplete[name], 'place_changed', function() {
var currentState = jQuery("#input_54_1").val();
then you can check that the autocomplete state matches the currentState.
if (state !== currentState) {
alert(`Only addresses in ${currentState} are allowed to be selected`);
return;
}
jQuery('#input_'+form_id+'_'+field_id+'_1').val(addressLine1);
That prevents any autocomplete results that are outside of the desired state, from being added to the form.