W1492046
W1492046

Reputation: 31

Using for loop to display JSON contents in HTML div

I am trying to display the contents of my JSON into the div class "network-info". I believe what is being written first is then overwritten by what is next in the array. What can I use to circumvent this and show everything?

    $(function() {

        var netinfo = function(data) {
            for (var i = 0; i < data.length; i++) {
                $(".network-info").html(
                    "<hr>" +
                    "<p> Adapter Name: " + data[i].name + "</p>" +
                    "<p> IP Address:  " + data[i].ip + "</p>" +
                    "<p> MAC Address:  " + data[i].mac + "</p>" +
                    "<p> Adapter ID:  " + data[i].id + "</p>" +
                    "<hr>"
                )
            }
        };

        $.ajax({
            url: "http://127.0.0.1:8080/dashboard?context=netadapters&node=5",
            dataType: 'json',
            crossDomain: true,
        }).done(function(data) {
            netinfo(data);
        });

    });

Upvotes: 0

Views: 1652

Answers (2)

freefaller
freefaller

Reputation: 19953

You are correct, the content of the .network-info element is being overwritten on each iteration of the loop.

I would suggest concatenating the string, and then setting the .html at the end. This way the browser does not have to parse the HTML and update the DOM each time...

 var netinfo = function(data) {
    var htmlResult = "";
    for (var i = 0; i < data.length; i++) {
        htmlResult +=
            "<hr>" +
            "<p> Adapter Name: " + data[i].name + "</p>" +
            "<p> IP Address:  " + data[i].ip + "</p>" +
            "<p> MAC Address:  " + data[i].mac + "</p>" +
            "<p> Adapter ID:  " + data[i].id + "</p>" +
            "<hr>"
        )
    }
    $(".network-info").html(htmlResult);
};

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65795

Instead of writing the output directly to HTML, build up a string and then inject the string, like this:

    var netinfo = function(data) {
        var output = "";
        for (var i = 0; i < data.length; i++) {
            output +=
                "<hr>" +
                "<p> Adapter Name: " + data[i].name + "</p>" +
                "<p> IP Address:  " + data[i].ip + "</p>" +
                "<p> MAC Address:  " + data[i].mac + "</p>" +
                "<p> Adapter ID:  " + data[i].id + "</p>" +
                "<hr>";
        }
        $(".network-info").html(output);
    };

This is actually better than appending data, because it only modifies the DOM once.

Upvotes: 1

Related Questions