Dennis Dennis - 5 months ago 12
Javascript Question

JavaScript and JSON: outputting different values in different tables

I'm getting JSON data from a file, and then trying to display the values from one name in one table and the values from another name in another table, but all the data is in both tables.

I cannot figure out how to isolate the values from one name and another in each table.

Here is my JSON:

{"launch_3d_link":"<a href='content/3d/speedswing1.html' target='ifrm'>Speed Swing 1</a>"},
{"launch_3d_link":"<a href='content/3d/speedswing2.html' target='ifrm'>Speed Swing 2</a>"},
{"launch_3d_link":"<a href='content/3d/speedswing3.html' target='ifrm'>Speed Swing 3</a>"},
{"launch_anim_link":"<a href='content/animated/animated1.html' target='ifrm'>Animated 1</a>"},
{"launch_anim_link":"<a href='content/animated/animated2.html' target='ifrm'>Animated 2</a>"},
{"launch_anim_link":"<a href='content/animated/animated3.html' target='ifrm'>Animated 3</a>"}


Here is my JavaScript (in header):

function loadFilesJson(data){
$.getJSON(url = 'lists/files.json',
function(data){
console.log(data);
});
}


Here are my Tables:

<div id="3d" class="panel">
<table id="3d" width="100%" style="margin-left:-15px;">
<script>
$(document).ready(function() {
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].launch_3d_link + "</td>");
$('#3d').append(tr);
}
});
});
</script>
</table>
</div>


and:

<div class="panel">
<table id="anim" width="100%" style="margin-left:-15px;">
<script>
$(document).ready(function() {
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].launch_anim_link + "</td>");
$('#anim').append(tr);
}
});
});
</script>
</table>
</div>


Small Update: I have changed my 'table' ID's to be unique. Code updated above.

Answer

There are two things.

First, like Tibo said, you should reference each table uniquely. The selector $('table') means it will add the current TR to any table on your site. Give an id to each table (like you have in the first case, 3d), and then select it directly.

<div id="3d" class="panel">
   ...
</div>

<div id="anim" class="panel">
   ...
</div>

Then you should also check if the attribute key exists in the current record. Like this:

for (var i = 0; i < data.length; i++) {
    if (typeof data[i].launch_anim_link != 'undefined') {
        tr = $('<tr/>');
        tr.append("<td>" + data[i].launch_anim_link + "</td>");
        $('#anim table').append(tr);
    }
}

If launch_anim_link does not exist it will skip it.

The same for the other table, but with launch_3d_link instead and selecting the proper table $('#3d table').append(tr).

Comments