Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a working script loading AJAX file using $.getJSON and loading it into 2 html tags. I would like to extend the JSON file and feed different data to some 30 tags. JSON string is defined the same as the tag Id which I thought would be useful in some loop to shorten the code, but I do not know how to define the loop.

How can I simplify the assignment of JSON values into tags .html to avoid 30 lines of $('Id').html(data.string) in my script?

received JSON data format: {"itemp1":"24","itemp1d":"8"}

tags with defined Ids:

<p id="itemp1" class="dfont1"></p>      
<p id="itemp1d" class="dfont3"></p>

working function - to be simplified for 30 tags:

function GetIndexData() {
    var param = "&nocache=" + Math.random() * 1000000;
    $.getJSON( 'index.js' , param , function(data) {
        console.log(data);
        $('#itemp1').html(data.itemp1);
        $('#itemp1d').html(data.itemp1d);
        // ... 30x

        // ? how to simplify this part with some loop?

    });
    setTimeout(GetIndexData, 5000);
}
share|improve this question

3 Answers 3

Since the object property keys and the element id looks the same, use $.each() to iterate through all properties of data and set the value

function GetIndexData() {
    var param = "&nocache=" + Math.random() * 1000000;
    $.getJSON('index.js', param, function (data) {
        $.each(data, function (key, val) {
            $('#' + key).html(val);
        })
    });
    setTimeout(GetIndexData, 5000);
}
share|improve this answer

Just loop your data object :

function GetIndexData() {
    var param = "&nocache=" + Math.random() * 1000000;
    $.getJSON( 'index.js' , param , function(data) {
        console.log(data);
        for(var id in data) {
            $('#'+id).html(data[id]);
        }
    });
    setTimeout(GetIndexData, 5000);
}
share|improve this answer

It's something like:

for(var key in data) {
    $("#"+key).html(data[key]);
} 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.