Lookup City by Zipcode for your WordPress form
Example JavaScript code and form elements code to lookup a city based on entered zipcode on your WordPress forms. You can change the region by setting the country as parameter if needed.
<script>
(function(){
var lookupCityByZipcode = function(zipCode){
var apiKey = 'XXXXX-XXXXX-XXXXX'; // Replace with your actual API key
var country = 'Netherlands'; // You can use the full country name or its ISO code (e.g., 'NL')
var field = document.querySelector('.super-form input[name="city"]');
fetch('https://maps.googleapis.com/maps/api/geocode/json?address='+zipCode+','+country+'&key='+apiKey).then(response => response.json()).then(data => {
if (data.status === 'OK') {
var city = data.results[0].address_components.find(component =>
component.types.includes('locality')
);
if (city) {
console.log('City:', city.long_name);
field.value = city.long_name;
} else {
console.log('City not found for this ZIP code.');
field.value = '';
}
SUPER.after_field_change_blur_hook({el: field});
} else {
console.error('Error:', data.status);
}
}).catch(error => console.error('Error fetching data:', error));
};
var debounceTimer, inputField = document.querySelector('.super-form input[name="enter_zipcode"]');
inputField.addEventListener('input', function(event) {
// Clear the existing timer if it's still running
clearTimeout(debounceTimer);
// Set a new timer for 1 second (1000 milliseconds)
debounceTimer = setTimeout(function() {
// Call the API or function after 1 second of inactivity
console.log('API called with value: ' + event.target.value);
// Add your API call function here
lookupCityByZipcode(event.target.value);
}, 1000);
});
})();
</script>Last updated