1

I'm trying to use innerHTML to display a variable that runs through a loop in a json file and adds onto itself, but when it is added with innerHTML, it shows as 0. I used console.log to make sure it was adding the numbers the way it should, and it definitely was, so I'm not quite sure what the problem is (Go easy on me, I literally started Javascript today).
Console.log: https://i.stack.imgur.com/0eSKH.png
How it looks in the webpage: https://i.stack.imgur.com/fGMK5.png
My Javascript:

window.onload = function() {
//Creates variable count
var count = 0;
//Runs through json file in a loop so the count can find the object amount
$.getJSON("/quake/quake.txt", function(json1) {
    $.each(json1, function(key, data) {         
        count = count + 1;
        count = count - (Number(data.mag) < 3.1);
        console.log(count);
    });
});
//Displays count in element with ID quakecount
document.getElementById("quakecount").innerHTML += "Magnitude 3.1+ Earthquakes Displayed: " + count;

}

1 Answers1

0

$.getJSON is asynchronous, it doesn't wait for file to be loaded, it moves to next line to therefore everytime you get 0, move your innerHTML in this function it will work fine.:

window.onload = function() {
//Creates variable count
var count = 0;
//Runs through json file in a loop so the count can find the object amount
$.getJSON("/quake/quake.txt", function(json1) {
    $.each(json1, function(key, data) {         
        count = count + 1;
        count = count - (Number(data.mag) < 3.1);
        console.log(count);
    });
//Displays count in element with ID quakecount
document.getElementById("quakecount").innerHTML += "Magnitude 3.1+ Earthquakes Displayed: " + count;

});
}
Ajay Narain Mathur
  • 5,326
  • 2
  • 20
  • 32