1

I have a function that checks for a div, and if it exists it fills it with the matching data from a JSON array. The Div and the data have the same id & key, so I want to be able to put those in a string for a more elegant solution. However, the final element of trying to apply the string element to the data key doesn't seem to be working. I get "Cannot read property '0' of undefined"

Original code:

$.getJSON('myDataUrl', function(data) {
if ($("#title").length){document.getElementById("title").innerHTML=data.title};
if ($("#noun").length){document.getElementById("noun").innerHTML=data.noun};
if ($("#_id").length){document.getElementById("_id").innerHTML=data._id};
if ($("#owner_id").length){document.getElementById("owner_id").innerHTML=data.owner_id};
}); 

The more 'elegant' solution I'm trying to reach:

$.getJSON('myDataUrl', function(data) {
var contentString = "name,noun,_id,owner_id";
var splitContent;
splitContent = contentString.split(",");
for(i = 0; i < splitContent.length; i++)
           {if ($("#" + splitContent[i]).length){
               document.getElementById(splitContent[i]).innerHTML=data.splitContent[i];
               };
               }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Paul Aston
  • 135
  • 12
  • You don't need to check for length if using jQuery – A. Wolff Dec 01 '14 at 19:18
  • I went by this accepted answer to check if a div exists http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery – Paul Aston Dec 01 '14 at 19:24
  • 1
    You don't need to check for element existence using jQuery because empty jQuery object can still be handled without throwing error – A. Wolff Dec 01 '14 at 19:26

3 Answers3

2

Looks like should be enough:

$.getJSON('myDataUrl', function (data) {
    for (var k in data) {
        $("#" + k).html(data[k]);
    }
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • Works like a charm. Thanks. And makes my 'elegant' idea look like my grandma in high heels. I'll mark as answered once the time limit expires – Paul Aston Dec 01 '14 at 19:27
0

The problem is data.splitContent[i]. That should be data[splitContent[i]]. That is, you want to use the current key (e.g. name) as a key in the data object.

0

You could also use jQuery's Map.

  $.map(data, function(value, key) {
    $("#" + key).html(value);
  });

Here's the working JSBin : http://jsbin.com/tocege/2/edit?html,js,output

Pascal Boutin
  • 1,220
  • 2
  • 9
  • 22