I am unable to set all three values (state, city, zip) to default (Sitka, Alaska, 99801) if only one of them returns ‘undefined’.
We are using this code in Unbounce page builder with MaxMind geo location finder.
$(window).on('load', function() {
$.getScript('//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js', function() {
geoip2.city(function(geoipResponse) {
let city = geoipResponse.city.names.en || 'Sitka'; // Default city to 'Sitka' if undefined
let state = geoipResponse.subdivisions[0].names.en || 'Alaska'; // Default state to 'Alaska' if undefined
let zip = geoipResponse.postal.code || '99801'; // Default zip to '99801' if undefined
$('#lp-pom-form-520 #State').val(state);
$('#lp-pom-form-520 #City').val(city);
$('#lp-pom-form-520 #Zip').val(zip);
}, function(error) {
console.error('Error fetching geoip data:', error);
});
});
});
I also tried this, but it doesnt worked:
<script>
$(window).on('load', function() {
$.getScript('//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js', function() {
geoip2.city(function(geoipResponse) {
let city = geoipResponse.city.names.en || 'Sitka';
let state = geoipResponse.subdivisions[0].names.en || 'Alaska';
let zip = geoipResponse.postal.code || '99801';
// Set default values if any of the fields is undefined
if (!city || !state || !zip) {
city = 'Sitka';
state = 'Alaska';
zip = '99801';
}
$('#lp-pom-form-520 #State').val(state);
$('#lp-pom-form-520 #City').val(city);
$('#lp-pom-form-520 #Zip').val(zip);
}, function(error) {
console.error('Error fetching geoip data:', error);
});
});
});
</script>
2
Answers
It’s too complex to use one-line logic (too many permutations) so I’d use a counter instead:
If I got your criteria wrong then you should make it clearer.
If any one undefined should trigger default values, then use one-line logic…
Btw, what you’ve got there doesn’t test undefined but a logical NOT…
Your test is only useful for boolean values and is equivalent to saying…
You won’t be able to catch undefined values with an exclamation mark.
In your second attempt, you forgot to remove the default values when declaring the variables, this is what it should be: