Create html table from comma separated strings javascript - javascript

I am trying to write a Javascript function which writes the text to (eventually) create the following html tables (I will be passing different length arguments to it to create hundreds of tables):
<table>
<tr><td><u>School</u></td>
<td><u>Percent</u></td>
<tr><td>School 1: </td>
<td>Percent1</td></tr>
<tr><td>School 2: </td>
<td>Percent2</td></tr>
<tr><td>School 3: </td>
<td>Percent3</td></tr>
</table>
The inputs that I have are comma separated strings:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
The function needs to be passed school_list and pct_list, and return a string of the html table code above.

Something like this:
var schoolArr = school_list.split(',');
var pctArr = pct_list.split(',');
var table = "<table>";
for (var i=0; i< schoolArr.length; i++) {
table = table + "<tr><td>"+ schoolArr[i]+"</td><td>"+ pctArr[i] +"</td></tr>";
}
table = table + "</table>";
return table;

You can try below code with Jsfiddle demo ::
function createTable(tab) {
var tar = document.getElementById(tab);
var table = document.createElement('TABLE');
table.border = '1';
var tbdy = document.createElement('TBODY');
table.appendChild(tbdy);
for (var j = 0; j < 4; j++) {
var tr = document.createElement('TR');
tbdy.appendChild(tr);
for (var k = 0; k < 2; k++) {
var td = document.createElement('TD');
td.width = '100';
if (k == 0) td.innerHTML = "School" + (j + 1);
else td.innerHTML = "Percent" + (j + 1);
tr.appendChild(td);
}
}
tar.appendChild(table);
}
createTable('tab');
<div id="tab"></div>

var schools = school_list.split(/,\s*/g).join('</td><td>');
var pcts = pct_list.split(/,\s*/g).join('</td><td>');
return '<table><tr><td>' + schools + '</td></tr><tr><td>' + pcts + '</td></tr></table>'
or a better approach is to construct the whole table in DOM and place it in document directly.
function appendTD(tr, content) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
var table = document.createElement('table');
school_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
pct_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
someParent.appendChild(table);

var numberOfSchools = school_list.split(',');
var numberOfPercent = pct_list.split(',');
var htmlOutput= '<table><tr><td><u>School</u></td><td><u>Percent</u></td>';
for(var i = 0 ; i < numberOfSchools.length; i++)
{
htmlOutput += "<tr><td>" + numberOfSchools[i] + "</td>";
htmlOutput += "<td>"+numberOfPercent[i] +"</td></tr>"
}
htmlOutput += "</table>"
And return htmlOutput

Here's a DOM method, highlighs why innerHTML is so popular. DOM methods are pretty fast in execution lately, but the amount of code is a bit tiresome unless there's a good reason to use it.
The amount of code can be significantly reduced with a couple of helper functions so it is on par with innerHTML methods:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
function makeTable(schools, percents) {
// Turn input strings into arrays
var s = schools.split(',');
var p = percents.split(',');
// Setup DOM elements
var table = document.createElement('table');
var tbody = table.appendChild(document.createElement('tbody'));
var oRow = document.createElement('tr');
var row;
oRow.appendChild(document.createElement('td'));
oRow.appendChild(document.createElement('td'));
table.appendChild(tbody);
// Write header
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode('School'));
row.childNodes[1].appendChild(document.createTextNode('Percent'));
// Write rest of table
for (var i=0, iLen=s.length; i<iLen; i++) {
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode(s[i]));
row.childNodes[1].appendChild(document.createTextNode(p[i]));
}
document.body.appendChild(table);
}
It can be called after the load event, or just placed somewhere suitable in the document:
window.onload = function() {
makeTable(school_list, pct_list);
}

Related

How to create table and set values to table cells using values in the same function

This block of code is to create 3 arrays with the values pulled from the user's input in a popup menu in the HTML file, but the values here are needed to fill in the table below.
var arrM = new Array; var arrT = new Array; var arrA = new Array;
arrM[0] = mod0.mod.value; arrT[0] = mod0.target.value; arrA[0] = mod0.actual.value;
arrM[1] = mod1.mod.value; arrT[1] = mod1.target.value; arrA[1] = mod1.actual.value;
arrM[2] = mod2.mod.value; arrT[2] = mod2.target.value; arrA[2] = mod2.actual.value;
arrM[3] = mod3.mod.value; arrT[3] = mod3.target.value; arrA[3] = mod3.actual.value;
arrM[4] = mod4.mod.value; arrT[4] = mod4.target.value; arrA[4] = mod4.actual.value;
arrM[5] = mod5.mod.value; arrT[5] = mod5.target.value; arrA[5] = mod5.actual.value;
arrM[6] = mod6.mod.value; arrT[6] = mod6.target.value; arrA[6] = mod6.actual.value;
arrM[7] = mod7.mod.value; arrT[7] = mod7.target.value; arrA[7] = mod7.actual.value;
arrM[8] = mod8.mod.value; arrT[8] = mod8.target.value; arrA[8] = mod8.actual.value;
arrM[9] = mod9.mod.value; arrT[9] = mod9.target.value; arrA[9] = mod9.actual.value;
the code in between the block above and the block below(not shown here) is just to compute the average values and does not interact with the block below
the code below is to create a table with the same number of rows as the number of rows the user filled in the popup menu.
var tableGenerator = document.getElementById("tableGenerator");
tbl = document.createElement('table');
tbl.style.width = '500px';
tbl.style.height = '100px';
tbl.style.border = '1px solid black';
tbl.style.margin = '50px';
tbl.style.float = 'left';
if (j < 6) {
j = 6;
}
for (var a = 0; a < j+1; a++) {
var tr = tbl.insertRow();
for (var b = 0; b < 3; b++) {
if (a == j && b == 3) {
break;
} else {
var td = tr.insertCell();
td.appendChild(document.createTextNode(""));
td.style.border = '1px solid black';
if (a == 0 && b == 0) {
var newtext = document.createTextNode(Text);
var celltext = "Year " + year.value + " Semester " + semester.value;
td.appendChild(document.createTextNode(celltext));
td.setAttribute('colSpan', '3'); break;
}
//this else block below here obviously doesn't work, but this idea is there and I want something that
//works like the pseudo code below
else {
for (a = 1; a < j; a++) {
tbl[a][0] = arrM[a];
tbl[a][1] = arrT[a];
tbl[a][2] = arrA[a];
}
}
}
}
}tableGenerator.appendChild(tbl);
I am very unfamiliar with HTML/JS/CSS, is it possible for us to access cell values of a table as if it is an array? or is there any better way to do this?
In JavaScript you'll need to either create text nodes and assign the content of that node, or assign the content to the textContent, innerText or innerHTML properties to give the table cells their values.
td.textContent = 'Hello'; // This is the preferred property for text.
The help you achieve this it would be wise to structure your data in a way that you can loop over, because you're basically doing the same thing in a specific order. For example:
var data = [
arrM,
arrT,
arrA
];
This will put your arrays in another array. Now you can loop over the data array and create a table row for each array, and a table cell for each item in the nested array.
for (var i = 0; i < data.length; i++) {
// ... create table row.
for (var j = 0; j < data[i].length; j++) {
// ... create table cell and assign textContent property.
}
}
Examine the example below. It's a runnable version of the thing I've explained above. I hope it helps you out.
function createTable(headers, values) {
var table = document.createElement('table');
// Build <thead>
var tableHeader = table.createTHead();
// Create <tr> inside <thead>
var tableHeaderRow = tableHeader.insertRow();
for (var i = 0; i < headers.length; i++) {
// Create <th>
var tableHeaderCell = document.createElement('th');
// Set text of <th> to value in array.
tableHeaderCell.textContent = headers[i];
// Add <th> to <tr> inside <thead>
tableHeaderRow.appendChild(tableHeaderCell);
}
// Build <tbody>
var tableBody = table.createTBody();
for (var j = 0; j < values.length; j++) {
// Create <tr> inside <tbody>
var tableBodyRow = tableBody.insertRow();
for (var k = 0; k < values[j].length; k++) {
// Create <td> inside <tr>
var tableBodyCell = tableBodyRow.insertCell();
// Set text of <td> to value in array.
tableBodyCell.textContent = values[j][k];
}
}
// Add <table> to the <body>
document.body.appendChild(table);
}
var titles = [
'One',
'Two',
'Three'
];
var characters = [
['Batman', 'Robin', 'Batgirl'],
['Joker', 'Two-Face', 'Poison Ivy'],
['James Gordon', 'Alfred Pennyworth', 'Clayface']
];
createTable(titles, characters);

How to dynamically add <a> in a html table?

I have a table generated from an array. I'm looking to add a hyperlink to the entire first column of the <tbody> and only the first column.
I am able to add the <a> after the table is created, but then it doesn't actually contain the url within it, it simply appends to what already exists.
Specifically, how can I add a hyperlink to the first column of the
<tbody>?
Generally, as the table is being made, how can I specify different
things (anchors, classes, styles, etc.) for different columns?
http://jsfiddle.net/nateomardavis/n357gqo9/10/
$(function() {
google.script.run.withSuccessHandler(buildTable)
.table();
});
//TABLE MADE USING for
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
var getTbody = document.getElementById('tbody');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column[j]));
row.appendChild(cell);
//NEXT TWO LINES DO NOT WORK
var firstCol = getTbody.rows[i].cells[0];
firstCol.setAttribute('class', 'TEST');
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
/* WORKS AFTER TABLE IS CREATED BUT CAN'T CAPUTRE INTERNAL LINK
var getTbody = document.getElementById('tbody');
for (var i = 0; i < getTbody.rows.length; i++) {
var firstCol = getTbody.rows[i].cells[0]; //first column
//firstCol.style.color = 'red';
//firstCol.setAttribute('class', 'TEST');
var link = document.createElement('a');
firstCol.appendChild(link);
}
*/
}

Having trouble trying to style duplicates

I'm checking for duplicates in a table. What I'm trying to accomplish is when I display the first column if it is the same value as the previous row I don't want to display the value. I'm finding the duplicates but I get an error when I try to hide them by using display. style ="none"; My code is below.
I'm Thanking You In Advance
PD
var data=[['e',0,1,2,3,4], ['a',54312,235,5,15,4], ['a',6,7,8,9,232],
['a',54,11235,345,5,6], ['b',0,1,2,3,4], ['b',54312,235,5,15,4],
['c',62,15,754,93,323], ['d',27,11235,425,18,78], ['d',0,1,2,3,4],
['d',54312,235,5,15,4], ['e',6,7,8,9,232], ['e',54,11235,345,5,6],
['e',0,1,2,3,4], ['e',54312,235,5,15,4], ['e',62,15,754,93,323],
['e',27,11235,425,18,78]];
//Create a HTML Table element.
var table = document.createElement("TABLE");
var somedata = document.createElement("TD");
var dvTable = document.getElementById("dvTable");
var elems = document.getElementsByClassName("tableRow");
//Get the count of columns.
var columnCount = data[0].length;
//Add the data rows.
for (var i = 0; i < data.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
//Searching for duplicates
var num = data[i][0];
for (var otherRow = i + 1; otherRow < data.length; otherRow++) {
var dup = data[otherRow][0];
console.log("What is the dup" + dup);
if (num === dup)
{
console.log("duplicate");
dvTable[i].style.display = "none";
}
}
var cell = row.insertCell(-1);
cell.innerHTML = data[i][j];
cell.innerHtml = myZero;
}
}
dvTable is an HTML table element. You can't access the row using dvTable[i].
Try -
dvTable.rows(i).cells(j).style.display = none;

Outputting a 3D array as a table

Im making a blackjack game for an assignment and have arrays for leaderboard and cards.
I want to print the leader board like this. CARDS(in individual cells)| TOTAL.
help would be appreciated, thanks
function makeTable(leaderBoard) {
var table = document.createElement('table');
for (var i = 0; i < leaderBoard.length; i++) {
var row = document.createElement('tr');
for (var j = 0; j < leaderBoard[i].length; j++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
document.getElementById('leaderBoard').innerHTML = table;
}
Maybe the example input isn't in the correct format, but reusing a predefined table and html table functions such as insertRow and insertCell (not necessarily better, but they can be easier on the eye than createElement and append) :
<div id="leaderBoard"><table id=leaderTable></table></div>
function updateleaderboard(leaderBoard) {
var table = document.getElementById('leaderTable');
while(table.rows.length > 0) table.deleteRow(0); //remove prev values, if any
for (var i = 0; i < leaderBoard.length; i++) { //If the function is always used on a winner (no ties), the loop isn't really needed
var row =table.insertRow();
var arrCards = leaderBoard[i++];
var total = row.insertCell();
total.className = 'res';
total.textContent = leaderBoard[i];
arrCards.forEach(function(c,ind){
row.insertCell(ind).textContent = c;
});
}
}
var cards = [['Q','4','5'],19];
updateleaderboard(cards);
Fiddle
function makeTable(leaderBoard) {
var table = document.createElement('table');
var row = document.createElement('tr');
for (var i = 0; i < leaderBoard[0].length; i++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[0][i];
row.appendChild(cell);
}
var cell = document.createElement('td');
cell.textContent = "Total: " + leaderBoard[1];
row.appendChild(cell);
table.appendChild(row);
document.getElementById('leaderBoard').appendChild(table);
}
var userCards = ["Card 1", "Card 2", "Card 3"];
var userTotal = 10;
makeTable([userCards, userTotal]);
http://jsfiddle.net/25kg3nnq/

Problem on using appendChild or innerHtml

I want to append my tr and td into tbody by using javascript not jQuery. Currently I am using jquery .html() I want to change it with Javascript.
var arrStrData = [];
for (i = 0; i < objData.length; i++) {
arrStrData.push("<tr>");
arrStrData.push("<td>");
arrStrData.push(objData[i].FirstName);
arrStrData.push("</td>");
arrStrData.push("<td>");
arrStrData.push(objData[i].LastName);
arrStrData.push("</td>");
arrStrData.push("<td>");
arrStrData.push(objData[i].Gender);
arrStrData.push("</td>");
arrStrData.push("<td>");
arrStrData.push(objData[i].Country);
arrStrData.push("</td>");
arrStrData.push("<td>");
arrStrData.push(objData[i].Password);
arrStrData.push("</td>");
arrStrData.push("</tr>");
}
$("tbody").html(arrStrData.join(''));
As a minimal change to your current code, you can follow it with:
var div = document.createElement('div');
div.innerHTML = '<table><tbody>' + arrStrData.join('') + '</tbody></table>';
var tbody = document.getElementsByTagName('tbody')[0];
tbody.parentNode.replaceChild(
div.getElementsByTagName('tbody')[0], tbody
);
A more general version might be:
var tbody = document.getElementsByTagName('tbody')[0];
var frag = document.createDocumentFragment();
var oRow = document.createElement('tr');
var oCell = document.createElement('td');
var propArray = ['FirstName','LastName','Gender',
'Country','Password'];
var row, cell, obj;
for (var i=0, iLen=objData.length; i<iLen; i++) {
row = oRow.cloneNode(false);
o = objData[i]
for (var j=0, jLen=propArray.length; j<jLen; j++) {
cell = oCell.cloneNode(false);
cell.appendChild(document.createTextNode(o[propArray[j]]));
row.appendChild(cell);
}
frag.appendChild(row);
}
tbody.appendChild(frag);
The above are general approaches that you can adapt to your circumstance.
Will only work if there is only one tbody element (just as your jQuery example).
document.getElementsByTagName("tbody")[0].innerHTML=arrStrData.join('');
jsFiddle Demo
You'd be better of defining an id on your table or tbody and using document.getElementById().
Please see the following URL on implementing addRow in a table using native javascript.
http://www.mredkj.com/tutorials/tableaddrow.html
As your already using jQuery why not use it to help you, that's what it's there for afterall.
var useKeys = ['FirstName', 'LastName', 'Gender', 'Country', 'Password'],
html = '';
for (var i = 0; i < objData.length; i++) {
var row = $(useKeys).map(function(value, key) {
var value = objData[i][key];
return '<td>' + (value == undefined ? '' : value) + '</td>';
}).get();
html += '<tr>' + row + '</tr>';
}
$('tbody').html(html);
Working fiddle

Categories

Resources