I have Javascript function and I want to check multiple if statements in return.
If the value exist or is not null then it should return a row with information,
I am not sure how to do this, I am thinking something like this, E.g:
function format(d){
return '<table cellpadding="5" cellspacing="0" border="0">' +
if (name) {
'<tr>' +
'<td>Name:</td>' +
'<td>' + d.name + '</td>' +
'</tr>' } +
if (place)
'<tr>' +
'<td>Place:</td>' +
'<td>' + d.place + '</td>' +
'</tr>' } +
if (date) {
'<tr>' +
'<td>Date:</td>' +
'<td>' + d.date + '</td>' +
'</tr>' } +
'</table>';
}
Like Daniel pointed out, you could build the string on your way out like this:
function myFormat(d) {
let result = '<table cellpadding="5" cellspacing="0" border="0">';
if (name){
result += '<tr>' + '<td>Name:</td>' + '<td>' + d.name + '</td>' + '</tr>';
}
if (place){
result += '<tr>' + '<td>Place:</td>' + '<td>' + d.place + '</td>' + '</tr>';
}
if (date){
result += '<tr>' + '<td>Date:</td>' + '<td>' + d.date + '</td>' + '</tr>';
}
result += '</table>';
return result;
}
Html elements could be combined together as well to make it simpler like this:
'<tr><td>Place:</td><td>' + d.name + '</td></tr>'
I see that you can create a template for row. Why not to use a separate function:
formatRow(value, label)
'formatRow' function can use if statement to check if value is empty and decide to return a row or empty string for concatenation.
function formatRow(value, label){
if(value) {
return '<tr>' +
'<td>' + label + '</td>' +
'<td>' + value + '</td>' +
'</tr>';
}
return '';
}
Then run it within format() function for each property that you want to use.
function createCell(text){
const td = document.createElement('td');
td.textContent=text;
return td
}
function createRow(data, key){
row = document.createElement('tr');
row.appendChild(createCell(key[0].toUpperCase() + key.substring(1) + ':' ))
row.appendChild(createCell(data[key]))
return row;
}
function format(d){
table = document.createElement('table');
table.setAttribute("cellpadding", "5");
table.setAttribute("border", "0");
table.setAttribute("cellspacing", "0");
Object.keys(d).forEach(key => table.appendChild(createRow(d, key)))
return table
}
document.body.appendChild(format({data: '5 feb 2021', name: 'John', place: 'New York' }))
document.write('<hr>')
document.body.appendChild(format({data: '5 feb 2021', name: 'John' }))
document.write('<hr>')
document.body.appendChild(format({data: '5 feb 2021' }))
I have this table
<table id="player_info">
<tr>
<th>Position</th>
<th>Club</th>
<th>Points</th>
<th>Matches Played</th>
<th>Wins</th>
<th>Draws</th>
<th>Losses</th>
<th>Goals For</th>
<th>Goals Against</th>
<th>Goal Difference</th>
<th>Form</th>
</tr>
</table>
And I have this function which iterates through JSON keys and creates a new table cell with each key. I would like to have the logo of each club appear next to its name in the table cell. The logo URL is stored in the JSON.
My current code
data.api.standings[0].forEach(elements => {
var tr = document.createElement('tr');
var img = new Image();
img.src = elements.logo;
tr.innerHTML = '<td>' + elements.rank + '</td>' +
'<td>' + elements.teamName + img + '</td>' +
'<td>' + elements.points + '</td>' +
'<td>' + elements.all.matchsPlayed + '</td>' +
'<td>' + elements.all.win + '</td>' +
'<td>' + elements.all.draw + '</td>' +
'<td>' + elements.all.lose + '</td>' +
'<td>' + elements.all.goalsFor + '</td>' +
'<td>' + elements.all.goalsAgainst + '</td>' +
'<td>' + elements.goalsDiff + '</td>' +
'<td>' + elements.forme + '</td>';
table.appendChild(tr);
});
However I am getting the team name and [object HTMLImageElement] and no image.
In your case you can do this instead
var img = '<img src="' + elements.logo + '" />'
instead of making an img element
i have this code:
for (var i = 0; i < data.times.length; ++i) {
var time = formatTime(data.times[i].time);
tableContent += '<tr><td>' + data.times[i].destination.name + '</td><td id="appendLate' + i + '">' + time + '</td><td>' + data.times[i].track + '</td><td>' + data.times[i].train_type + '</td><td>' + data.times[i].company + '</td></tr>'
// laat vertragingen zien (BETA)
if (data.times[i].delay / 60 >= 1) {
$('#appendLate' + i + '').append("+" + data.times[i].delay / 60).addClass("late");
}
}
table.html(tableContent);
}
The if statement appends stuff and adds a class. i know it wont work like this.. but i cant seem to get how it WIL work.. Can some one help?
See it live: http://codepen.io/shiva112/pen/JGXoVJ?editors=001
Well, you're basically almost there. The right way to do it is to build the entire string before doing any DOM manipulation, since DOM operations are very slow (relatively).
Let's say your index.html looks like:
<html>
<head>
<title>Cool site!</title>
</head>
<body>
<table id="myCoolTable"></table>
</body>
</html>
Then your JavaScript simply becomes:
var tableContent = '';
for (var i = 0; i < data.times.length; ++i) {
var time = formatTime(data.times[i].time);
tableContent += '<tr>'
+ '<td>' + data.times[i].destination.name + '</td>';
if (data.times[i].delay / 60 >= 1) {
tableContent += '<td id=\'appendLate\'' + i + ' class=\'late\'>' + time + '</td>' + '+' + (data.times[i].delay / 60);
} else {
tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>';
}
tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>'
+ '<td>' + data.times[i].track + '</td>'
+ '<td>' + data.times[i].train_type + '</td>'
+ '<td>' + data.times[i].company + '</td>'
+ '</tr>';
}
$('#myCoolTable').html(tableContent);
What this does is build the HTML for the entire table. Then update the table only once. Hope it helps!
my jQuery creates tables, but currently it keeps repeating the new tables under the previous ones when 'submit' button is clicked. How do I toggle it so it clears the previous table before showing the new table?
Any help would be great thanks!
<script type="text/javascript">
function call_everybody(){
display_results_table();
display_cyclist_results_table();
display_cyclist2_results_table();
}
function display_results_table() {
$("medal_table").empty();
$('<table id = "results_table">').appendTo('#medal_table');
$.get("sam2.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (results_obtained) {
$('<tr><td>Rank</td>' +
'<td>Country Name</td>' +
'<td>Population</td>' +
'<td>GDP</td>' +
'<td>Gold</td>' +
'<td>Silver</td>' +
'<td>Bronze</td>' +
'<td>Total</td></tr>').appendTo('#results_table');
for (var i = 0; i <= results_obtained.length; i++) {
$('<tr><td>' + (i+1) + '</td>' +
'<td>' + results_obtained[i].country_name + '</td>' +
'<td>' + results_obtained[i].population + '</td>' +
'<td>' + results_obtained[i].gdp + '</td>' +
'<td>' + results_obtained[i].gold + '</td>' +
'<td>' + results_obtained[i].silver + '</td>' +
'<td>' + results_obtained[i].bronze + '</td>' +
'<td>' + results_obtained[i].total + '</td></tr>').appendTo('#results_table');
}
},'json');
$('</table>').appendTo('#medal_table');
}
function display_cyclist_results_table() {
$("cyclist_table").empty();
$('<table id = "cyclist_results_table">').appendTo('#cyclist_table');
$.get("sam3.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (cyclist_results_obtained) {
$('<tr><td>Country id</td>' +
'<td>Name</td>' +
'<td>Gender</td>' +
'<td>Sport</td></tr>').appendTo('#cyclist_results_table');
for (var j = 0; j <= cyclist_results_obtained.length; j++) {
$('<tr><td>' + cyclist_results_obtained[j].iso_id + '</td>' +
'<td>' + cyclist_results_obtained[j].name + '</td>' +
'<td>' + cyclist_results_obtained[j].gender + '</td>' +
'<td>' + cyclist_results_obtained[j].sport + '</td></tr>').appendTo('#cyclist_results_table');
}
},'json');
$('</table>').appendTo('#cyclist_table');
}
function display_cyclist2_results_table() {
$("cyclist2_table").empty();
$('<table id = "cyclist2_results_table">').appendTo('#cyclist2_table');
$.get("sam4.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (cyclist2_results_obtained) {
$('<tr><td>Country id</td>' +
'<td>Name</td>' +
'<td>Gender</td>' +
'<td>Sport</td></tr>').appendTo('#cyclist2_results_table');
for (var j = 0; j <= cyclist2_results_obtained.length; j++) {
$('<tr><td>' + cyclist2_results_obtained[j].iso_id + '</td>' +
'<td>' + cyclist2_results_obtained[j].name + '</td>' +
'<td>' + cyclist2_results_obtained[j].gender + '</td>' +
'<td>' + cyclist2_results_obtained[j].sport + '</td></tr>').appendTo('#cyclist2_results_table');
}
},'json');
$('</table>').appendTo('#cyclist2_table');
}
</script>
<title>sam.php</title>
</head>
<body>
<form name="form">
<table>
<tr><td><input name="Country_1" id="Country_1" value="GBR" type="text"></td></tr>
<tr><td><input name="Country_2" id="Country_2" value="USA" type="text"></td></tr>
<td><input id='toggle' type="button" value="Cyclist Comparison" onclick="call_everybody()"/></td></tr>
</table>
</form>
<div id = "toggle_table">
<div id="medal_table"></div>
<div id="cyclist_table"></div>
<div id="cyclist2_table"></div>
</div>
</body>
You need to add -
$('#results_table').remove();
Prior to -
$('<table id = "results_table">').appendTo('#medal_table');
In the below code am having one table with values from database.After executing the the query if am having 5 values am getting only the first value in my table(inside pop up).in this html() function how can i add the foreach and type of parametrs for for each,
i used ajax,json,jquery
My code is;
success: function (msg) {
var data = $.parseJSON(JSON.stringify(eval("(" + msg.d + ")")));
$('<div></div>')
.appendTo('body')
.html('<div><b>SHAREHOLDER DETAILS</b></br>' + data.Id + '</div>' +
'<div>' + data.name + '</div>' +
'<div>' + data.Id + '</div>' +
'<table border="1" style="background-color:silver;"><tr>' +
'<td>' + 'OwnedBy' + '</td>' +
'<td>' + 'ShareClass' + '</td>' +
'<td>' + 'EffectiveInterest' + '</td>' +
'<td>' + 'DeemedInterest' +'</td>' +
'<td>' + 'SharesOwned' + '</td>' +
'<td>' + 'SharesIssued' + '</td>' +
'</tr>' +
'<tr>' +
'<td>' + data.Id +'</td>' +
'<td>' + data.share + '</td>' +
'<td>' + data.effect + '</td>' +
'<td>' + data.deemed + '</td>' +
'<td>' + data.owned + '</td>' +
'<td>' + data.issued + '</td>' +
'</tr>' +
'</table>')
.dialog({
modal: true,
title: '<div>' + data.Id + '</div>',
zIndex: 10000,
autoOpen: true,
position: ['right', 'top'],
width: 'auto',
height: 'auto',
modal: false,
resizable: false,
closeOnEscape: false,
show: "slide",
hide: "explode",
close: function (event, ui) {
$(this).remove();
}
});
},
I don't know how much effort you've put into solving this on your own, but in the interest of fairness, I'll explain the thought process a bit. What you need to consider is conceptualizing and separating the "rows" from the "general entity", eg, "I have a table with rows which contain data".
The loop itself runs when creating the rows, and has to be performed as a separate action from creating the table itself. Even if you embed the loop logic into the table construction itself (as far as the markup generation itself goes, which I consider bad practice), you still have to consider each row as the result of a loop run, distinct from the table, thead, and tbody. Note, even with the rows (tr), you have another (potential) loop requirement in each cell in the row (td). In this case you don't need a loop at that level, but that points to conceptualizing the rudiments of loop design and utilization.
Here is a method using jQuery element caching and a jQuery.each() loop, which is a type of foreach loop. Note, in Javascript there is no dedicated foreach loop; there is, however, for(var i in object), which allows you to iterate over an object of this kind.
$(document).ready(function(){
var $table = $('<table>'),
$tbody = $('<tbody>'),
$thead = $('<thead>' +
'<tr>' +
'<th>OwnedBy</th>' +
'<th>ShareClass</th>' +
'<th>EffectiveInterest</th>' +
'<th>DeemedInterest</th>' +
'<th>SharesOwned</th>' +
'<th>SharesIssued</th>' +
'</tr>' +
'</thead>'),
$tr = $('<tr>'),
data = {
grp1: {
Id: 'id1',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
},
grp2: {
Id: 'id2',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
},
grp3: {
Id: 'id3',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
}
};
$table
.append($thead, $tbody)
.appendTo(document.body);
jQuery.each(data, function(i, val) {
$tr.clone()
.appendTo($tbody)
.append(
'<td>' + val.Id +'</td>' +
'<td>' + val.share + '</td>' +
'<td>' + val.effect + '</td>' +
'<td>' + val.deemed + '</td>' +
'<td>' + val.owned + '</td>' +
'<td>' + val.issued + '</td>'
);
});
});
http://jsfiddle.net/YFwTe/
You need some sort of iterator function, as you have it the code will only pull the first value.
My suggestion would be to use .each:
var element = $('<table></table>').appendTo('body');
jQuery.each(data, function(i, val) {
element.append(
'<tr>' +
'<td>' + val.Id +'</td>' +
'<td>' + val.share + '</td>' +
'<td>' + val.effect + '</td>' +
'<td>' + val.deemed + '</td>' +
'<td>' + val.owned + '</td>' +
'<td>' + val.issued + '</td>';
'</tr>';
);
});
Haven't tested it just because I don't have a data string, but hopefully that gets you close.