Javascript Question

Adding some error catching in jQuery in a case the user JSON response does not contain a an item

I have a jQuery giving me a problem in implementing

if statement
with it. I am outputting an item called
city
, and if from the response its not available, I like to show: City Not Found.

This is what i have done:





$.get("http://freegeoip.net/json/", function(parseResponse) {
if ($("#address") != null){
$("#address").html("City: " + parseResponse.city);
$("#details").html(JSON.stringify(parseResponse, null, 4));
}
else {
$("#city").html("City: Not Found");
}
}, "jsonp");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>






What am i doing wrong? Am trying to get city written out and when its not available, it shows
Not Found


Answer

By using ||, you can use the trailing option instead of the initial option if the initial option is null, empty, etc.

   

 $.get("http://freegeoip.net/json/", function(parseResponse) {
  if ($("#address") != null){
        $("#address").html("City: " + (parseResponse.city || "Not Found."));
        $("#details").html(JSON.stringify(parseResponse, null, 4));
    }
  else  {
        $("#city").html("City: Not Found");
    }
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>

Comments