join() JS for HTML tables - javascript

I need to use join() as JS own method to add a table format to the values in those arrays.
This is an example of my two arrays to diplay, and the table layout should look like this.
This is the part of my code; ovbiously is not working ok, because Im getting a wrong "L" table style format when it runs.
I know its look terrible to parse HTML like that, but this code is in
Google Apps Scripts, so this table is gonna be send it by email.
Any idea how to get the proper format?
Thanks.
|-------|-------|
| user | skill |
|-------|-------|
| user | skill |
|-------|-------|
body +=
"<table style=" + STYLE.TABLE + ">" +
outUsers.join("<tr><td style=" + STYLE.TD + ">") + "</td></tr>" +
outSkills.join("<tr><td style=" + STYLE.TD + ">") + "</td></tr>" +
"</table>";

In this case Array.prototype.join() doesn't do the job I'd use Array.prototype.reduce() instead
Here is an example of what it could look like:
EDIT according to PHPglue comment to have both users and skills on the same row:
var body ='';
var outUsers = ['me', 'you', 'her'],
outSkills = ['eating', 'sleeping', 'working hard'],
STYLE = {
TABLE: "border: red;",
TD: "border: blue;"
},
getTR = function (prev, curr, index) {
return prev + '<tr>' + openingTD + curr + '</td>' + openingTD + outSkills[index] + '</td></tr>';
};
var openingTD = '<td style="' + STYLE.TD + '">';
body += '<table style="' + STYLE.TABLE + '">' +
outUsers.reduce(getTR, '') +
"</table>";

I think this is what you need to see:
var table = '<table><tbody>';
for(var i=0,l=outUsers.length; i<l; i++){
table += '<tr><td>'+outUsers[i]+'</td><td>'+outSkills[i]+'</td></tr>';
}
table += '</tbody></table>';
You should style with CSS. You should read my comments above, as well.

Related

add Dagre D3 note or descriptor outside of node

Is there an easy way to add a note or discriptor to a node? So the node label is in the node, but a secondary descriptor is above or below the node?
I am thinking I might need to create the nodes and then loop over then and try to add the descriptor, but thought I would see if there is an easier way.
const g = new dagreD3.graphlib.Graph({ compound: true })
.setGraph({})
.setDefaultEdgeLabel(() => {});
g.setNode('N1', {
label: 'N1',
shape: 'circle',
});
d3.selectAll('g.node').each(function(d) {
...
});
edit: Ended up doing something similar to what
KateJean answered with. Used the label to create an overlay.
'label=<' +
'<table border="0">' +
'<tr>' +
'<td height="16"></td>' +
'</tr>' +
'<tr>' +
'<td cellspacing="0" cellpadding="0" height="30" width="100">' +
`<font color="${color}"><b>${category}</b></font>` +
'</td>' +
'</tr>' +
'<tr>' +
`<td>${name}</td>` +
'</tr>' +
'</table>' +
'>'
I forked this a while ago to play around with (not my original work, so apologies to the original author), but I think the solution in this fiddle may be what you're looking for.
You can define a header element and a body and use that as your "label" element. Here, bootstrap is used for the styling.
https://jsfiddle.net/KateJean/9gtezLfq/
var g = new dagreD3.graphlib.Graph().setGraph({});
for (var i = 0; i < 7; i++) {
var html = '<div class="panel panel-primary">'
html += '<div class="panel-heading">' + i + ' Panel</div>'
html += '<div class="panel-body"><p style= "color: black;">Test<p></div>'
html += '</div>'
g.setNode(i, {
labelType: "html",
label: html,
padding: 0
})
}

.html() jQuery function return NaN

I have
<div id="tablePlace"></div>
And
if ($('#radioOne').is(':checked') == true) {
$("#tablePlace").html(" ");
$("#tablePlace").append(htmlTable); //htmlTable is a string that contains an html table code
loadNestedTable(temp);
}
It works but in the div I find NaN.
If I comment $("#tablePlace").append(htmlTable);, NaN doesn't appear.
Why?
UPDATE
htmlValue code:
var tab = '<table id="decretoSingolo">'+
+'<thead>'
+ '<tr>'
+ '<th>Ente</th>'
+ '<th>CUP</th>'
+ '<th>Decreto impegno</th>'
+ '<th>Data decreto impegno</th>'
+ '<th>Importo impegno</th>'
+ '<th>Finanziato MIUR</th>'
+ '<th>Importo pagato</th>'
+ '<th>Importo in pagamento</th>'
+ '</tr>'
+ '</thead>'
+ '<tbody>'
+ '</tbody>'
+'</table>'
+'<div style="display:none">'
+ '<table id="dettagliDecretoSingolo">'
+ '<thead>'
+ '<tr>'
+ '<th>Progressivo pagamento</th>'
+ '<th>Data decreto</th>'
+ '<th>Numero decreto pagamento</th>'
+ '<th>Tipo pagamento</th>'
+ '<th>Importo in pagamento</th>'
+ '<th>Nota decreto</th>'
+ '</tr>'
+ '</thead>'
+ '<tbody>'
+ '</tbody>'
+ '</table>'
+'</div>';
htmlTable value:
<table id="myTable">NaN<tr><th>Ente</th><th>CUP</th><th>Decreto impegno</th><th>Data decreto impegno</th><th>Importo impegno</th><th>Finanziato</th><th>Importo pagato</th><th>Importo in pagamento</th></tr></thead><tbody></tbody></table><div style="display:none"><table id="myTableDetails"><thead><tr><th>Progressivo pagamento</th><th>Data decreto</th><th>Numero decreto pagamento</th><th>Tipo pagamento</th><th>Importo</th><th>Nota</th></tr></thead><tbody></tbody></table></div>
NaN appears after .append(). There is a problem in the htmlTable code?
The problem is that you have a unary + in your code:
var tab = '<table id="decretoSingolo">'+
+'<thead>'
// ^--- Here
To fix it:
Remove one of the +s. Usually it's best to use the + at the end of the previous line, to avoid issues with automatic semicolon insertion.
Why you're getting NaN:
It's a unary + because it follows the + at the end of the previous line, with whitespace in-between them (so it's not ++ as I initially suggested).
That unary + will try to take its operand (the string that follows it) and convert it to a number, and if that can't be done will yield NaN. Then the operands to the + on the previous line are a string and a number, so that addition operator converts the string to number and adds it to NaN (which yields NaN).
You can see it here:
var tab = '<table id="decretoSingolo">'+
+'<thead>'
+ '<tr>';
document.body.innerHTML = tab;
Side note: There's no need to do .html(" ") and then .append(htmlTable), just do .html(htmlTable).
You have double plus sign + in the following lines, remove one :
var tabellaDecretoSingolo = '<table id="decretoSingolo">'+
+'<thead>'
+ '<tr>'
Should be :
var tabellaDecretoSingolo = '<table id="decretoSingolo">'
+'<thead>'
+ '<tr>'
Hope this helps.
First, you can optimise your javascript:
if ($('#radioOne').is(':checked') == true) {
$("#tablePlace").html(" ");
$("#tablePlace").append(htmlTable); //htmlTable is a string that contains an html table code
loadNestedTable(temp);
}
by
if ($('#radioOne').is(':checked') == true) {
$("#tablePlace").html(htmlTable); //html() replace all content of your element child.
loadNestedTable(temp);
}
Also, you've a problem when you define your "htmlTable" value
<table id="myTable">NaN<tr> [...]
check after your ">" of your element if you don't add a NAN var...

Inserting custom text in JS output

I have below line in my js code. i runs from 0 to 2. I want to put a custom text in place of: ' + info[i] + ' for each of the i's(over iterations of i). How do I do that?
for(var i=0; i < origins.length-1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + info[i] + '</td><td>' + origins[i] + '</td><td></td><td>' + destinations[i+1] + '</td><td></td><td>' + results[i+1].distance.text + '</td></tr>';
}
. I want to put a custom text in place of: ' + info[i] + ' for each of the i's(over iterations of i).
Not sure what is "custom text" but assume your custom text should be in an array:
var customText = ["Custom text for i=0",
"Custom text for i=1",
"Custom text for i=2"];
for(var i=0; i < origins.length-1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + customText[i] + '</td><td>' + //....
}
Also how to align the out-put of the code at the center of my webpage?
This is connected to CSS rather than with JS. Use CSS property text-align: center for a table, div or wharever you want to center.
If the custom text isn't in a variable, just put it directly into the HTML that you're generating:
output += '<tr><td>Custom Text</td><td>' + origins[i] + '</td><td></td><td>' + destinations[i+1] + '</td><td></td><td>' + results[i+1].distance.text + '</td></tr>';

How to make the table in javascript

I have this code to make the data available in table format but the table head and row appear as two different body, how do i work with that
$("#container").html("<table> <th>Name</th> <th>Address</th> <th>Sex</th> <th>Email</th>")
for (var i = 0; i < data.length; i++) {
$("#container").append("<tr><td>" +
data[i].name + "</td><td>" +
data[i].address + "</td><td>" +
data[i].sex + "</td><td>" +
data[i].email + "</td><tr>"
);
}
$("container").append("</table>")
This is what I get
I want the whole table, not two seperate buddies.
var htmlTable = '<table><tr><th>Name</th><th>Adress</th><th>Sex</th> <th>Email</th></tr>';
for(var i = 0; i < data.length; i++) {
htmlTable += '<tr><td>' + data[i].name + '</td><td>' + data[i].adress + '</td><td>' + data[i].sex + '</td><td>' + data[i].email + '</td></tr>';
}
htmlTable += '</table>';
$('#container').html(htmlTable);
Add the table to the DOM at once, otherwise the browser will have problems rendering it.
You can't append <table> and </table> separately, appending DOM elements (by setting innerHTML behind the scene) is not the same as string concatenation. Browser detects invalid markup and fixes it accordingly by adding missing parts of the table. So as the result you get one table after first append, and in the loop you are appending rows into #container, not the table, which is rendered incorrectly.
To fix try something like this:
var $table = $("#container").html("<table><tr><th>Name</th><th>Address</th><th>Sex</th><th>Email</th></tr></table>");
for (var i = 0; i < data.length; i++) {
$table.append("<tr><td>" + data[i].name + "</td><td>" + data[i].address + "</td><td>" + data[i].sex + "</td><td>" + data[i].email + "</td></tr>");
}
Note, I also cached $table variable so you don't query DOM in each iteration.
Also pay attention to closing tags, in your code you have couple of problems like <tr> where it should be </tr>.
You need to add <tr> too for <th>:
$("#container").html("<table> <tr><th>Name</th> <th>Address</th> <th>Sex</th> <th>Email</th></tr></table>")

Add anchor point to headers?

I have a really big html-document consisting of a number of <h4> headers accompanied by a short <p> 'body'.
I need to add an anchor point (is it the correct term, btw?) to each of the headers.
I'm iterating over the headers, and adding them to a menu-ul:
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
$("#menu").html("<ul>")
while (x<y){
arrayOfHeaders[x] = "<li><a href='#" + x +"'>" + headz[x].innerText + "</a></li>";
$("#menu").append(arrayOfHeaders[x])
x++;
}
$("#menu").append("</ul>")
I need a way to attach the anchor points to the headers.
Edit: To clarify - what i need is the add a name-tag to each of the -elements.
The first header should be edited from '<h4>' header'</h4>' to '<h4 name="0">'...
Without editing the html, of course.
Set ids to the if they do not have one.
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
var str = "<ul>";
while (x<y){
var elem = headz[x];
var id = elem.id || "heading_" + x;
elem.id = id;
str += "<li><a href='#" + id +"'>" + elem.innerText + "</a></li>";
x++;
}
$("#menu").append( str + "</ul>");
and FYI innerText is not cross browser friendly.
jQuery solution
var str = "<ul>";
$("h4").each(
function(i){
var id = this.id || "header_" + i;
this.id=id;
str += '<li>' + this.innerHTML + '</li>';
}
);
str += "</ul>";
$("#menu").append(str);
Since you used jquery already, thought id write it all in it:
var html = '<ul>';
$('h4').each(function (index, header) {
html += '<li>' + header.html() + '</li>';
});
html += '</ul>';
$('#menu').append(html);
This might solve your problem
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
var html = "<ul>";
while (x<y){
html += "<li><a href='#" + headz[x].id +"'>" + headz[x].innerText + "</a></li>";
x++;
}
$("#meny").append( html + "</ul>")
This one is similar to rissicay's answer but I think it's more concise:
var html = []; // create an empty array to store iterated html in
// loop over every heading...
$('h4').each(function(index) {
// and add it to array previously created
html.push("<li><a href='#" + index +"'>" + $(this).html() + "</a></li>");
// add name attribute to heading
$(this).attr('name', index);
});
// finally, append all to menu together with unordered list
$('#menu').append('<ul>' + html.join() + '</ul>');
Basically, try to minimize dom manipulation (.append(), .prepend(), .html()) as much as possible
I think the concept you refer to is sometimes known as an "internal link" - see here under the second section "HTML Links - The id Attribute".
Now looking at your example code you are clearly using jQuery so why not make the most of it?
$("h4").each(function() {
$("#links").append("<a href='#" + this.id + "'>link to " + this.id + "</a><br /><br />");
});
See the following fiddle - http://jsfiddle.net/r0k3t/PhrB6/
Hope that helps.

Categories

Resources