0

I have an ajax call that creates html elements based on a loop. Some of the data in my call is empty and will display as undefined, I am trying to find a way to have it display as zero.

success: function(response) {
    var results = response.results;
    var html = '';

    for (var i = 0; i < results.length; i++){
         html += '<span class="test">' + results[i].code + '</span>'
     }
}
$('#mydiv').html(html);

The above code would display like this.

123
456
undefined
678
undefined

How can i suppress the undefined to print like

123
456
0
678
0
user2168066
  • 627
  • 11
  • 21

4 Answers4

1

you can try (results[i].code == null)

success: function(response) {
    var results = response.results;
    var html = '';

    for (var i = 0; i < results.length; i++){
         var ht = (results[i].code == null)? 0 : results[i].code;
         html += '<span class="test">' + ht  + '</span>'
     }
}
$('#mydiv').html(html);

Ref : How to determine if variable is 'undefined' or 'null'?

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
0

just use if else

 if( results[i].code ===undefined){

    html += '<span class="test">0</span>';

  }else{

    html += '<span class="test">' + results[i].code + '</span>';
  }
JYoThI
  • 11,977
  • 1
  • 11
  • 26
0
success: function(response) {
    var results = response.results;
    var html = '';

    for (var i = 0; i < results.length; i++){
         html += '<span class="test">' + ((typeof results[i].code != "undefined") ? results[i].code : 0) + '</span>'
     }
}
$('#mydiv').html(html);
Sagar Jajoriya
  • 2,377
  • 1
  • 9
  • 17
0

You will need to add a condition to check if the value is undefined (might also be good to check for null values as well) and then display "0" if the value is undefined (or null).

You can update your code to something like this to make sure that your undefined values are printed as "0":

success: function(response) {
    var results = response.results;
    var html = '';

    for (var i = 0; i < results.length; i++){
        var resultCode = results[i].code;
        if (typeof resultCode === "undefined" || resultCode === null){
            resultCode = 0;
        }
        html += '<span class="test">' + resultCode + '</span>'
    }
}
$('#mydiv').html(html);
ttimmons
  • 91
  • 2
  • 8