Reputation: 1156
I'm using jQuery's each/getJSON to loop through a my data.json
file, grab and format the data, and output it onto my page inside the #output
div.
It works as expected, except for the [object HTMLElement]
that's strangely prepended to the rendered HTML.
$.getJSON( 'json/data.json', function ( data ) {
var output;
$.each( data, function ( index, entry ) {
output += '<div class="entry" id="' + entry.date + '">';
$.each( entry.exercises, function ( index, exercise ) {
var i = 1;
output += '<table class="exercise"><tr><th>' + exercise.name
+ '</th><th>Weight</th><th>Reps</th></tr>';
$.each( exercise.stats, function ( index, stat ) {
output += '<tr><td>SET ' + i++ + '</td><td><input type="number" placeholder="'
+ stat.weight + '"></td><td><input type="number" placeholder="'
+ stat.reps + '"></td></tr>';
});
output += '</table>';
});
output += '</div>';
}); // each
$( '#output' ).html( output );
}); // getJSON
data.json
[
{
"date" : 12252014,
"exercises" : [
{
"name" : "Squats",
"stats" : [
{ "weight" : 135, "reps" : 5 },
{ "weight" : 225, "reps" : 10 },
{ "weight" : 315, "reps" : 15 }
]
},
{
"name" : "Bench",
"stats" : [
{ "weight" : 435, "reps" : 20 },
{ "weight" : 525, "reps" : 15 },
{ "weight" : 615, "reps" : 30 }
]
},
{
"name" : "Rows",
"stats" : [
{ "weight" : 735, "reps" : 35 },
{ "weight" : 825, "reps" : 40 },
{ "weight" : 915, "reps" : 45 }
]
}
]
}
]
HTML error:
<div id="output">
"[object HTMLElement]"
<div class="entry" id="12252014" style="display: none;">
<table class="exercise">
<tbody>
<tr>
<th>Squats</th>
<th>Weight</th>
<th>Reps</th>
</tr>
<tr>
<td>SET 1</td>
<td><input type="number" placeholder="135"></td>
<td><input type="number" placeholder="5"></td>
</tr>
<tr>
<td>SET 2</td>
<td><input type="number" placeholder="225"></td>
<td><input type="number" placeholder="10"></td>
</tr>
<tr>
<td>SET 3</td>
<td><input type="number" placeholder="315"></td>
<td><input type="number" placeholder="15"></td>
</tr>
</tbody>
</table>
[...]
</div>
</div>
Why's [object HTMLElement]
being added to the output?
Upvotes: 0
Views: 305
Reputation: 8520
This for me looks like the variable output
allready was in use before and filled with a html element.
In your case it's your wrapper div with the id output
which is exposed as a global variable.
You should be able to overcome this by giving output en initial value:
var output = '';
Because using var
does not cleanup an existing variable:
var output = 'Lorem ipsum';
var output;
alert(output)
Upvotes: 3
Reputation: 7244
Change
var output;
to
var output = '';
and this will fix your problem. There is probably an element in your HTML document with id="output", by default, elements with ids are exposed as global variables of the same name, so <a id="hello">text</a>
will appear as window.hello
.
Upvotes: 3