Search code examples
javascriptjqueryundefinedmaxmindunbounce

Set 3 values to default values if only one of them returns 'undefined'


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>

Solution

  • In your second attempt, you forgot to remove the default values when declaring the variables, this is what it should be:

    let city = geoipResponse.city.names.en;
    let state = geoipResponse.subdivisions[0].names.en;
    let zip = geoipResponse.postal.code;