1

I want JS to fill my span only if API gave an actual string for both fields. If it didn't then I want it to display default value only in one field. The default value is "Germany".

Here is my code:

$(document).ready(function () {
  $.get("https://api.ipdata.co?api-key=[APIKEY]", function (response) { 
    city = response.city;
    country_name = response.country_name;
    $("#city").html(city);
    $("#country_name").replaceWith(country_name);
  }, "jsonp"); 
});
<span id="city"></span>
<span id="country_name">Germany</span>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
DanielsV
  • 892
  • 1
  • 8
  • 26

2 Answers2

0

Firstly you should use text() not replaceWith() to set the innerText of the div. Secondly, you can use || to coerce a value if it's undefined, null, an empty string or any other falsy value. Try this:

$("#city").text(city || '');
$("#country_name").text(country_name || 'Germany');
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

If you want to populate both fields only if both fields are returned from the ajax request, you can simply wrap them in an if statement:

$.get("https://api.ipdata.co?api-key=[APIKEY]", (response) => {

 if(response.city && response.country_name){
  // same code here
 }

});
Rodolfo Rangel
  • 596
  • 1
  • 3
  • 15