Create HTML table from javascript array - javascript

I want to get all classes of the HTML element on my page, split it and store it in array. After that I want to write it into my table in the div with the id "table" which I already have.
So far I have this code:
var string = $('html').attr('class');
var array = string.split(' ');
var arrayLength = parseInt(array.length);
for (i=0; i<=arrayLength; i++) {
// code
}
<div id="test><!-- table goes here --></div>
Can you help me with the rest?
btw, the HTML element has the classes from a modernizr.js.
PS: The code is combination of pure JS and jQuery. Because I dont know how to get all classes of the HTML element in pure JS. Any Idea?

If you're trying to remove jQuery altogether use this:
// Get array of classes without jQuery
var array = document.getElementsByTagName('html')[0].className.split(/\s+/);
var arrayLength = array.length;
var theTable = document.createElement('table');
// Note, don't forget the var keyword!
for (var i = 0, tr, td; i < arrayLength; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode(array[i]));
tr.appendChild(td);
theTable.appendChild(tr);
}
document.getElementById('table').appendChild(theTable);

if you have a table already in the html
<div id="test><table >
</table>
</div>
you can simply append new rows to it,
var string = $('html').attr('class');
var array = string.split(' ');
var arrayLength = parseInt(array.length);
for (i=0; i<=arrayLength; i++) {
$("#test table") .append('<tr><td>'+array[i]+'</td></tr>')
}

It is not clear if you want the class names per row or per column. These examples are one class name per row. Try this:
var elm = $('#test'),
table = $('<table>').appendTo(elm);
$(document.documentElement.className.split(' ').each(function() {
table.append('<tr><td>'+this+'</td></tr>');
});
I used native code to get the classNames of the HTML element: document.documentElement.className, but you might as well use $('html').attr('class').
A native JS example using innerHTML:
var d = window.document,
elm = d.getElementById('test'),
html = '<table>',
classes = d.documentElement.classNames.split(' '),
i = 0;
for(; classes[i]; i++) {
html += '<tr><td>' + classes[i] + '</td></tr>';
}
elm.innerHTML = html + '</table>;

Related

HTML Table Row Creation

EDIT: With significant help from others, I was able to work up a solution.
I'm taking data from a Google Spreadsheet and then attempting to render it as an HTML table in a WebApp.
I'd like the data to show up like
<tr>
<td>
<td>
<td>
exactly how it looks in a spreadsheet, with each value in a separate cell.
Big picture, I'd like to be able to do different things to each <td>, so I want to make sure I structure the data in a usable way.
Code.GS
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function webAppTest() {
getTeamArray();
}
function getTeamArray() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange('A2:H1000');
var values = range.getValues();
//Logger.log(values);
var teamsArray = [];
for (var i = 0; i < values.length; ++i) {
var column = values[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
var colE = column[4];
var colF = column[5];
var colG = column[6];
var colH = column[7];
if (colA != '') {
teamsArray.push(values[i][0]);
teamsArray.push(values[i][3]);
teamsArray.push(values[i][4]);
}
}
var array2 = [];
while(teamsArray.length) array2.push(teamsArray.splice(0,3));
var lengthDivName2 = array2.length;
var widthDivName2 = array2[0].length;
//Logger.log(teamsArray);
Logger.log(array2);
//return teamsArray;
return array2;
}
Index.HTML Function
function buildOptionsList(teamsArray) {
var div = document.getElementById('myList');
for (var i = 0; i < teamsArray.length; i++) {
var tr = document.createElement('tr');
var td = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
var iD = td.setAttribute('id',teamsArray[i]);
td.appendChild(document.createTextNode(teamsArray[i]));
div.appendChild(tr);
div.appendChild(td);
}
}
</script>
</head>
<body>
<div id="myList" class="connectedSortable">MY LIST</div>
</body>
</html>
ATTEMPT 1
ATTEMPT 2
I tried to change the array creation in code.gs which got all the correct data in the <tr> but didn't split into <td>s
I am not sure I understood the way you receive the data, but if teamsArray contain information about one line the solution would be something like this:
function buildOptionsList(teamsArray) {
var div = document.getElementById('myList');
var tr = document.createElement('tr');
for (var i = 0; i < teamsArray.length; i++) {
var td = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
var iD = td.setAttribute('id',teamsArray[i]);
td.appendChild(document.createTextNode(teamsArray[i]));
tr.appendChild(td);
}
div.appendChild(tr);
}
Use Array#map, Array#reduce, and Array#join to surround the elements of the inner array with the required HTML tags and then condense to a single string. Currently you have an implicit Array#toString call which creates a comma-separated string of the inner array's elements (the inner array is at teamData[i]), and thus you only have a single cell in your previous attempts' output.
This simple function assumes you aren't applying any column- or row-specific styles or attributes, so it can simply treat every <td> element equivalently. If you have symmetric styling to apply, you would want to process the headers/row variables with .map first (since you can then use the elements' indices) and then .join("") instead of just .join using the tag delimiters.
function getTableHTMLFrom(array, hasHeaders) {
if (!array || !array.length || !array[0].length)
return "";
const headerString = (hasHeaders ?
"<tr><th>" + array.shift().join("</th><th>") + "</th></tr>"
: "");
const tdTag = "<td class=\"ui-state-default\">";
const bodyString = array.reduce(function (s, row) {
s += "<tr>" + tdTag + row.join("</td>" + tdTag) + "</td></tr>";
return s;
}, "");
return "<table>" + headerString + bodyString + "</table>";
}
I found a solution (applied to Index.HTML) that worked based on THIS.
function buildOptionsList(array2) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
array2.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
buildOptionsList(array2);

How to add nested table to datatable?

I need to add a nested table to each row of a jquery datatable(using legacy datatables). So, I tried using example from datatables.net for child rows and modifying it to my needs as I need for the child rows to show at all times, rather than on clicking the parent row.Here is the code I am using both to build my inner table and then display it..
function buildInnerTable(){
var keys = Object.keys(reportApp.gridData),
len = keys.length,
j = 0,
prop,
value;
while (j < len) {
prop = keys[j];
value = reportApp.gridData[prop];
detLen = value.detail.length;
var rowVals = [];
for(var i = 0; i < detLen; i++){
tmpRow = "<tr><td>"+value.detail[i].invtid+"</td>"+
"<td>"+value.detail[i].bf+"</td>"+
"<td>"+value.detail[i].qtyship+"</td>"+
"<td>"+value.detail[i].ordqty+"</td>"+
"<td>"+value.detail[i].bf+"</td>"+
"<td>"+value.detail[i].exttreating+"</td>"+
"<td>"+value.detail[i].extpriceinvc+"</td>"+
"<td>"+value.detail[i].misc+"</td>"+
"<td>"+value.detail[i].extother+"</td>"+
"<td>"+value.detail[i].calcext+"</td></tr>";
rowVals.push(tmpRow);
}
setTableRow(rowVals , j);
j += 1;
}
function setTableRow(rowVals , ndx){
$("#gridTbl > tbody > tr:eq("+ ndx+ ")").after("<table><tr><th>InvtID</th>"+
"<th>Clss</th><th>Pieces</th><th>BilQty</th><th>BF</th><th>Treating</th>"+
"<th>Wood</th><th>NEED NAME</th><th>Other</th><th>Misc</th><th>Total</th></tr>"+
rowVals);
But, I am not getting what I need to get. What it looks like is that the datatables adds a new row and then sets the new table inside the first cell on new row. However, when I view source, that isn't what is happening at all. It closes the previous row and then inserts new table...
I am attaching a screenshot. What I need is for the details to show below the main item rows and to be aligned in same way. Any help in where I am wrong will be greatly appreciated.
Ok... Finally figured this out.
In order to make the view show normally, I had to add a new row to the datatable and then, in side that row, add my new table. However, this caused an indexing issue with the table. So, I had to check the index each time before I added new row. I am posting working code in the hope that it will help someone else.
function buildInnerTable(){
var keys = Object.keys(reportApp.gridData),
len = keys.length,
j = 0,
prop,
value;
while (j < len) {
prop = keys[j];
value = reportApp.gridData[prop];
detLen = value.detail.length;
var rowVals = [];
//THIS NEXT LINE IS WHERE I GET MY INDEX...
var ndx = ($("tr:contains("+value.invcnbr+ ")").index());
for(var i = 0; i < detLen; i++){
tmpRow = "<tr><td>"+value.detail[i].invtid+"</td>"+
"<td>"+value.detail[i].bf+"</td>"+
"<td>"+value.detail[i].qtyship+"</td>"+
"<td>"+value.detail[i].ordqty+"</td>"+
"<td>"+value.detail[i].bf+"</td>"+
"<td>"+value.detail[i].exttreating+"</td>"+
"<td>"+value.detail[i].extpriceinvc+"</td>"+
"<td>"+value.detail[i].misc+"</td>"+
"<td>"+value.detail[i].extother+"</td>"+
"<td>"+value.detail[i].calcext+"</td></tr>";
rowVals.push(tmpRow);
}
setTableRow(rowVals,ndx);
}
j += 1;
}
}
function setTableRow(rowVals,ndx){
var outerTbl = $('#gridTbl').DataTable();
var tr = $("#gridTbl > tbody > tr:eq("+ ndx+ ")");
//NOTE HOW I ADD A ROW AND THEN ADD NEW TABLE TO CELL IN THE ROW.
var innerTbl = "<tr><td colspan = 10><table style = 'background- color:#FFFFFF; width:100%; border:1px solid;'><tr><td>InvtID</td>"+
"<td>Clss</td><td>Pieces</td><td>BilQty</td><td>BF</td><td>Treating</td>"+
"<td>Wood</td><td>NEED NAME</td><td>Other</td><td>Misc</td><td>Total</td></tr>"+
rowVals + "</td></tr>";
tr.after(innerTbl).show();
}

Div's are being generated dynamically and even the (obj.search) fetches the data but nothing is being displayed in it. How do i display the data?

JS doesn't display the output
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.id = "div"+i;
divTag.className = "list";
document.getElementById('div'+i).innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
}
Image here
You missed adding the newly created element to the DOM. Example:
document.getElementById("yourDivContainer").appendChild(divTag);
Fiddle:
http://jsfiddle.net/mbpfgm49/
You need to append your div tags to some element (e.g: body), to make text appear on page
// Let's create some sample data
var obj = {
Search: []
}
var currentYear = (new Date).getFullYear();
for (var i = currentYear - 10; i <= currentYear; i++) {
obj.Search.push({
Title: 'Test',
Year: i
})
}
// Here goes your code fixed
for (var i = 0; i < obj.Search.length; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.className = "list";
divTag.innerHTML = obj.Search[i].Title + ' ' + obj.Search[i].Year;
document.body.appendChild(divTag);
}
Yes, you have to add the element to the DOM.
More basically, it is an anti-pattern to construct IDs for elements and use those as the primary means for referring to elements, by means of calling getElementById at every turn. I guess this approach is one of the many lingering after-effects of the jQuery epidemic.
Instead, keep references to elements directly in JS where possible, and use them directly:
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.className = "list";
parent.appendChild(divTag);
^^^^^^^^^^^^^^^^^^^^^^^^^^ INSERT ELEMENT
divTag.innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
^^^^^^ REFER TO ELEMENT DIRECTLY
}
To be absolutely pedantically correct, what you are creating is not a "tag", it's an "element". The element is the DOM object. The "tag" is the div which characterizes the element type.

Read td values by tr id from the same table

I am trying to read the values of table based on the tr id, but cannot wrap my head around how to do this.
// Id of the tr in question for example.row_17
var d =c["id"];
console.log(d);
// Here I can read all the td values, but I only want
// the ones inside the tr id = "row_17"
var cols =document.getElementById('report_table').getElementsByTagName('td'),
colslen = cols.length, i = -1; > while(++i < colslen)
{ console.log(cols[i].innerHTML);
}
Since you tagged it with jQuery, you can do it by doing something like this:
var id = c["id"];
// Select only the row with id specified in 'id' and loop through all 'td's' of that row.
$("#" + id).find("td").each(function()
{
// Log the html content of each 'td'.
console.log($(this).html());
});
Just in case you want a solution for JavaScript only (no jQuery):
var id = c["id"];
var tds = document.querySelectorAll('#' + id + ' td');
for(var i = 0; i < tds.length; i++) {
console.log(tds[i].innerHTML);
}
Demo

Could you please help me to highlight the selected HTML table row created dynamically through java script

Below is the JavaScript functionalities addRow() I have used to add the rows dynamically and now am trying to highlight the selected row with red color using rowhighlight() function.
/Function to addRows dynamically to the HTML table/
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var rowValues1 = finSumArr1[i].split("|");
tb=document.createElement("tbody");
var tbody=document.createElement("tbody");
table.appendChild(tbody);
var tr=document.createElement("tr");
tbody.appendChild(tr);
for(var k=0;k<=10;k++)//adding data to table dynamically
{
var td=document.createElement("td");
tr.appendChild(td);
var element1=rowValues1[k];
td.innerHTML =element1;
tr.onclick=function(){
rowhighlight(this);//calling the rowhighlight function
}
}
}
}
function rowhighlight(x)
{
var index = x.rowIndex;
document.getElementById("NotesFinancialSummary").rows [index].style.backgroundColor = "red";
}
One approach is to first loop through the other rows and remove the styling (really should be a class) then apply the styling (again, class) to the selected row.
Here's one way of doing it:
function rowHighlight() {
var selectedRows = document.getElementsByClassName('selected');
for (var n = 0; n < selectedRows.length; n++) {
selectedRows[n].className = '';
}
this.className = 'selected'
}
And here's a working example of it, though very simple: fiddle time!

Categories