Please take a look at this Fiddle.
Is there a better way of building a table with titles in the first cell of each row, like this:
<div id="area">
<table>
<thead>
<tr>
<th></th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Germany</td>
<td>Yes</td>
<td>No</td>
<td>Yes</td>
</tr>
.........
</tbody>
</table>
</div>
In building a string of HTML, I use an each(function)
for each returned object and then at the end set the div #area with the content. I can't think of a better way of doing this, but would like to know if there is a way to simplify the code. My actual JSON Data is way bigger than the example below, so the code would be very long and use far more each function in the buildup of the string.
JSON:
[{"title":"A","nation":"Germany,Japan","city":"Hamburg,Toyko","Name":"John,Peter,Tom"},{"title":"B","nation":"Japan,Italy","city":"Toyko","Name":"Adam,Tom"},{"title":"C","nation":"Germany","city":"Berlin,Hamburg","Name":"Mary,Tom"}]
Code:
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FRgDyl4%22&format=json&diagnostics=true&callback=",
success: function (data) {
var item_html="";
item_html += "<table><thead><tr><th></th>";
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
item_html += '<th>'+title+'</th>';
});
item_html += "</tr></thead><tbody><tr><td>Germany</td>";
$(data.query.results.json.json).each(function (index, item) {
var nations = item.nation.replace(/ /g,'').split(",");
console.log(nations);
if ($.inArray('Germany', nations) < 0)
{
item_html += "<td>No</td>";
}else{
item_html += "<td>Yes</td>";
}
});
item_html += "</tr><td>Berlin</td>";
$(data.query.results.json.json).each(function (index, item) {
var citys = item.city.replace(/ /g,'').split(",");
if ($.inArray('Berlin', citys) < 0)
{
item_html += "<td>No</td>";
}else
{
item_html += "<td>Yes</td>";
}
});
item_html += "</tr><td>Peter</td>";
$(data.query.results.json.json).each(function (index, item) {
var names = item.Name.replace(/ /g,'').split(",");
if ($.inArray('Peter', names) < 0)
{
item_html += "<td>No</td>";
}else
{
item_html += "<td>Yes</td>";
}
});
item_html += "</tr></tbody></table>";
$('#tablearea').append(item_html);
}
});
1 Answer 1
you can merge
var item_html="";
item_html += "<table><thead><tr><th></th>";
to
var item_html="<table><thead><tr><th></th>";
and i also cant see the id
"tablearea" in your html.
UPDATE:
by your fiddle link that tablearea is the id of a div and are you sure that you want to use $('#tablearea').append(item_html);
because it will append to div
everytimes whenever your ajax method called.
so better that you use
$('#tablearea').html(item_html);
<th>
if it's a title as well. \$\endgroup\$