Jeff Lamb
Jeff Lamb

Reputation: 5865

Dynamically assign values to IDs based upon AJAX content

I have some javascript:

eval('var incomingJSON =' + ajaxObj.responseText);
for (p in incomingJSON.common) {
    document.getElementById(p).value = incomingJSON.common.p;
} 

where ajaxObject.responseText is:

{
    "common": {
        "item1": "1",
        "item2": "2",
        "item3": "3",
        "item4": "4",
        "item5": "5" 
    }
}

The following line works:

document.getElementById(item1).value = incomingJSON.common.item1;

However, incomingJSON.common.p evaluates to "undefined". The left side of the assign works fine. What's the proper way to access the value in that object given the correct name?

Upvotes: 0

Views: 87

Answers (1)

Greg
Greg

Reputation: 321698

I think you're looking for the bracket notation syntax:

document.getElementById(p).value = incomingJSON.common[p];

Upvotes: 1

Related Questions