Create HTML table from JavaScript object - javascript
I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn.
Explanation
What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received.
You want to loop through the object. The best way to do so would be with a for loop, and making sure our looping variable remains valid for the length of our object (all its attributes).
The best way to get the length of a JSON object is through myJSONObject.length: You select the keys of myJSONObject and return their count.
You can access the values stored in your JSON Object the following way, in your for loop (assuming the looping variable defined is named i): myJSONObject[i].theAttributeIWantToGet
Price formatting breakdown
Now, those prices need to have a proper format, don't they? So we'll check if any of the value attribute has less than 2 characters after the . within them. If they do, we add another decimal 0. We also add a $ before writing the formatted value. Here is a breakdown of how it works:
obj[i].value.toString().substring(startIndex, length)
We want to check the length after the . sign, so our startIndex will be the position of this dot within our string.
obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)
We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe.
Final result: obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2
This will return true or false. If it's true: There's less than 2 digits after the dot !
We add the if statement and the last zero:
if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";
Also: Why I use innerHTML instead of appendChild().
Solution
JSFiddle
HTML
<table>
<tbody id="tbody"></tbody>
</table>
JSON
[{
"key": "apple",
"value": 1.90
}, {
"key": "berry",
"value": 1.7
}, {
"key": "banana",
"value": 1.5
}, {
"key": "cherry",
"value": 1.2
}]
JavaScript
Note: The JSON object will be named obj in this instance.
var tbody = document.getElementById('tbody');
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
/* Verification to add the last decimal 0 */
if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";
/* Must not forget the $ sign */
tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>";
/* We add the table row to the table body */
tbody.innerHTML += tr;
}
JSFiddle
It can be simply done by a small & smart process:
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th>Name</th>
<th width="20%">Age</th>
<th width="12%">Status</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var mainObj = [
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active"
}
];
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i].name + '</td>';
k+= '<td>' + mainObj[i].age + '</td>';
k+= '<td>' + mainObj[i].status + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
You can do something like this:
var table = document.createElement("table");
//Add a header
var header = document.createElement("tr");
var idHeaderCell = document.createElement("th");
var nameHeaderCell = document.createElement("th");
var relevanceHeaderCell = document.createElement("th");
header.appendChild(idHeaderCell);
header.appendChild(nameHeaderCell);
header.appendChild(relevanceHeaderCell);
table.appendChild(header);
//Add the rest of the data to the table
for(var i = 0; i < data.length; i++) {
var id = (i + 1);
var name = data[i].key;
var relevance = data[i].value;
var tr = document.createElement("tr");
var idCell = document.createElement("td");
var nameCell = document.createElement("td");
var relevanceCell = document.createElement("td");
idCell.appendChild(document.createTextNode(id));
nameCell.appendChild(document.createTextNode(name));
relevanceCell.appendChild(document.createTextNode(relevance));
tr.appendChild(idCell);
tr.appendChild(nameCell);
tr.appendChild(relevanceCell);
table.appendChild(tr);
}
Here a function for build a table from any collection (array of objects)
Table creator
const data=[
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active",
testing: 'Gooo!!'
}
]
const createTable=function(data){
const table = document.createElement("table");
const header = document.createElement("tr");
const keys=Object.keys(data[0])
console.log(keys)
for(const key of keys){
const th=document.createElement("th");
th.appendChild(document.createTextNode(key));
header.appendChild(th);
}
table.appendChild(header);
const len=data.length
for(const row of data) {
const tr = document.createElement("tr");
for(const key of keys){
const td = document.createElement("td");
const content=row[key] ||''
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
delete row[key]
}
/****
you can omit next cycle if all object have the same structor or if the first element of collection have all fields
****/
for(const key in row){
const th=document.createElement("th");
th.appendChild(document.createTextNode(key))
keys.push(key)
header.appendChild(th);
const td = document.createElement("td");
const content=row[key] ||''
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table
}
Array.map() combined with template literals comes in really handy for rendering HTML markup within Javascript for large objects in a scalable manner:
function tableMarkupFromObjectArray(obj) {
let headers = `
<th>Index</th>
${Object.keys(obj[0]).map((col) =>`
<th>${col}</th>`
).join('')}`
let content = obj.map((row, idx) => `
<tr>
<td>${idx}</td>
${Object.values(row).map((datum) => `
<td>${datum}</td>`
).join('')}
</tr>
`).join('')
let tablemarkup = `
<table>
${headers}
${content}
</table>
`
return tablemarkup
}
let myobj =[
{ "name": "apple", "rel": 1.90 },
{ "name": "berry", "rel": 1.7 },
{ "name": "banana", "rel": 1.5 },
{ "name": "cherry", "rel": 1.2 }
]
document.querySelector("#mydiv").innerHTML = tableMarkupFromObjectArray(myobj)
http://jsfiddle.net/4L7c5vad/
Here is my ES6 solution.
I have used the reduce operation to construct a Set storing the keys from all objects in the array:
function arrayToTable(data) {
const keys = [...data.reduce((all, obj)=>{
Object.keys(obj).forEach(key => all.add(key));
return all;
}, new Set())];
const header = keys.map(key => `<th>${key}</th>`).join('')
const tbody = data.map(row => keys.map(key => `<td>${row[key]}</td>`).join('')).map(row => `<tr>${row}</tr>`)
return `<table>
<thead><tr>${header}</tr></thead>
<tbody>${tbody}</body>
</table>`;
}
Iterate through the list and retrieve the data for each item this way (assuming your data is in a var called data):
for (var i = 0; i < data.length; i++) {
var id = i + 1;
var name = data[i].key;
var relevance = data[i].value;
}
Then, do something with the variables in each loop, print them out however you want.
I am not totally sure what you are asking for. The title of you post seems like you are looking for JSON.stringfy like mentioned in the previous answer but apparently you are not.
Are you trying to create and HTML list, ? Can you please try to explain your need again? I doubt what you are trying to do is complicated and I sure we can help you if you give a little more detail and purpose of what you are trying to do.
I am going to guess that you are trying to display HMTL by looping over you JSON object. Try this pure JavaScript example:
var fruits = JSON.parse('[{"key":"apple","value":1.90}, {"key":"berry","value":1.7}, {"key":"banana","value":1.5}, {"key":"cherry","value":1.2} ]');
var tbl = document.createElement('table');
var thead = document.createElement("thead");
var tbody = document.createElement("tbody")
var tr_head = document.createElement("tr");
var th_id = document.createElement("th");
var th_name = document.createElement("th");
var th_price = document.createElement("th");
th_id.textContent = "Id";
th_name.textContent = "Name";
th_price.textContent = "Price";
tr_head.appendChild(th_id);
tr_head.appendChild(th_name);
tr_head.appendChild(th_price);
thead.appendChild(tr_head);
for(var i = 0, j = fruits.length; i < j; i++) {
var tr_body = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_value = document.createElement("td");
td_id.textContent = i;
td_name.textContent = fruits[i].key;
td_value.textContent = fruits[i].value;
tr_body.appendChild(td_id);
tr_body.appendChild(td_name);
tr_body.appendChild(td_value);
tbody.appendChild(tr_body);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
console.log(tbl);
Maybe like this:
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var value = obj[key].toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
If case of nested structure (objects inside object) obj2htmltable() could call itself recursively:
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var item = obj[key];
var value = (typeof(item) === 'object') ? obj2htmltable(item) : item.toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
Related
How to print array data inside a table
So I have this code where I'm trying to print(physical print as in paper) a table when a button is clicked, which is populated with array data. I managed to print the array data but I can not seem to find on how to put this in a table. also is there a better way than document.write()I am not a huge fan of it ? var Obj = []; function printDiv(){ var divContents = document.getElementsByClassName("test") console.log(divContents) //if($("div").hasClass("test") == true){// can use jquery hasfind in order to check if acive class exists if yes get content of child divs //expand if this option is better //console.log('istrue'); //} for(var i = 0; i< divContents.length; i++){ Obj.push(divContents[i].textContent +'</br>') } var a = window.open('','','height=500,width=500'); a.document.write('<html>'); a.document.write('<body><h1>Div contents are<h1><br>'); a.document.write('<table><tbody><tr>') a.document.write('<td>'+ Obj.join(' ')+'<td>'); a.document.write('</tr></tbody></table></body></html>'); a.document.close(); a.print(); Obj = []; } expected outcome would be: work order and date are not yet populated this is just a test file to use in a bigger project. jsfiddle : https://jsfiddle.net/yLz7stxr/ thanks in advance.
here is the solution you just need to replace ${} in code link. code: https://jsfiddle.net/vnxd1pew/3/
I assume we got an array of objects here. const dataObject = {'name': null, 'age': null, 'favoriteFood': null}; let data = []; let row = {...dataObject}; row.name = 'John'; row.age = '10'; row.favoriteFood = 'Pancakes'; data.push(row); row = {...dataObject}; row.name = 'Jenny'; row.age = '11'; row.favoriteFood = 'Pie'; data.push(row); row = {...dataObject}; row.name = 'James'; row.age = '12'; row.favoriteFood = 'Fries'; data.push(row); // build table header let tableHeaderColumns = Object.keys(data[0]).map(colKey => `<th>${colKey}</th>`).join(''); const tableHeader = `<tr align=left>${tableHeaderColumns}</tr>`; // build table rows let i = 0; let tableRows = ''; let greyStyle = 'background-color: #EEE;'; data.forEach(function(rowObject) { const row = Object.values(rowObject).map(colValue => `<td>${colValue}</td>`).join(''); let rowStyle = ''; if(++i%2) { rowStyle = greyStyle; } tableRows += `<tr style='${rowStyle}'>${row}</tr>`; }); // build table (add desired styling) const table = `<table cellspacing=0 width=500 border=1 borderColor=#EEE style='border-collapse: collapse;'>${tableHeader}${tableRows}</table>`; // for demonstration display in div document.querySelector('div').innerHTML = table; <div />
How can I add a table column dynamically in JavaScript?
I have two arrays and need to write the data from both to two columns of a table. At this point I can write correctly data from the first array only and when I want to add the second array data, it gets added into rows. orderGelen and userNameArr are my arrays. Here you can see my code: for(let data of orderGelen){ dataHtmlIds += `<tr><td>${data}</td>`; } for(let usr of userNameArr){ dataHtmlUsr += `<td>${usr}</td></tr>`; } dataHtml = dataHtmlIds + dataHtmlUsr; console.log(dataHtml); And here I write that to table: function tableConfig() { tableBody.innerHTML = dataHtml; } How can I make the second column userNameArr data?
Try to put two arrays in one array like this const all = orderGelen.map((item, index) => ({ id: item, username: userNameArr[index] })); let html = '<table>'; for (let row of all) { html += `<tr><td>${row.id}</td><td>${row.username}</td></tr>`; } html+='</table>' console.log(html);
you could do something like var dataHtml = ""; for ( let i = 0, j = 0; i < userNameArr.length || j < orderGelen.length; i++, j++ ) { dataHtml += `<tr>`; dataHtml += `<td>${userNameArr[i] ? userNameArr[i] : ""}</td>`; dataHtml += `<td>${orderGelen[j] ? orderGelen[j] : ""}</td>`; dataHtml += `</tr>`; } and you could write to the table like function tableConfig() { tableBody.innerHTML = dataHtml; } Hope this helps
How to get the key names from the JavaScript array?
I am creating a page where I want to print the values like below the code snippet using the map function in JavaScript. var kvArray = [{a:1, b:2},{a:3, b:4},{a:5, b:6}]; function getValue(item,index) { var vm="<table/>" var fullValue =[item.a +" "+ item.b]; var v=vm+fullValue return v; } function myFunction() { document.getElementById("demo").innerHTML =kvArray.map(getValue).join(" ") } I am getting the output like this: 1 2 3 4 5 6 But I want the actual output like this: a b 1 2 3 4 5 6
Please see the following snippet for a working example: var kvArray = [{a:1, b:2},{a:3, b:4},{a:5, b:6}] var asCell = v => `<td>${v}</td>` var asRow = v => `<tr>${v}</tr>` $('#demo > thead > tr').html( Object.keys(kvArray[0]).map(key => asCell(key)) ) $('#demo > tbody').html( kvArray.map(entry => { return asRow(Object.keys(entry).map(k => { return asCell(entry[k]) }).join()) }) ) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="demo"> <thead> <tr></tr> </thead> <tbody></tbody> </table> I used Object.keys(kvArray[0]) to get the "column names".
var kvArray = [{a:1, b:2},{a:3, b:4},{a:5, b:6}]; function getValue(item,index) { var vm="<table/>" var fullValue =[item.a +" "+ item.b]; var v=vm+fullValue return v; } function createTable(kvArray) { var tableOpening="<table>"; var tableClosing="</table>"; var headerOpening= "<th>"; var headerClosing= "</th>"; var rowOpening= "<tr>"; var rowClosing= "</tr>"; var cellOpening= "<td>"; var cellClosing= "</td>"; // get the keys from the first element var keys = Object.keys(kvArray && kvArray[0]) ; // create a header var header = rowOpening; for (var keyIndex in keys) { header += headerOpening + keys[keyIndex] + headerClosing + "\n"; } header += rowClosing; var table = tableOpening + header; // create a row for each element for (var itemIndex in kvArray) { // open the row element var rowLine = rowOpening; for (var keyIndex in keys) { // fill the cells rowLine += cellOpening + kvArray[itemIndex][keys[keyIndex]] + cellClosing + "\n"; } // close the row element rowLine += rowClosing; // add the current row to the table table += rowLine; } // close the table table += tableClosing; return table; } Now just use this function for creating a table like so: document.getElementById("demo").innerHTML = createTable(kvArray); I know this is not as short as some of the answers given here, but it is much simpler to understand, as you obviously lack some concepts, namely your code was creating in each row and you were lucky it worked.
I want to display specific contents from JSON object into a table structure? how can i do that?
{"symbol":"DRREDDY","series":"EQ","openPrice":"3,132.00","highPrice":"3,229.90","lowPrice":"3,132.00","ltp":"3,206.35","previousPrice":"3,153.25","netPrice":"1.68","tradedQuantity":"74,165","turnoverInLakhs":"2,379.33","lastCorpAnnouncementDate":"18-Jul-2016","lastCorpAnnouncement":"Annual General Meeting\/ Dividend - Rs 20\/- PerShare"},{"symbol":"ACC","series":"EQ","openPrice":"1,567.00","highPrice":"1,606.85","lowPrice":"1,564.85","ltp":"1,594.25","previousPrice":"1,568.10","netPrice":"1.67","tradedQuantity":"1,03,292","turnoverInLakhs":"1,645.62","lastCorpAnnouncementDate":"22-Feb-2016","lastCorpAnnouncement":"Dividend - Rs 6\/- Per Share"}, {"symbol":"ACC","series":"EQ","openPrice":"1,567.00","highPrice":"1,606.85","lowPrice":"1,564.85","ltp":"1,594.25","previousPrice":"1,568.10","netPrice":"1.67","tradedQuantity":"1,03,292","turnoverInLakhs":"1,645.62","lastCorpAnnouncementDate":"22-Feb-2016","lastCorpAnnouncement":"Dividend - Rs 6\/- Per Share"} This is the JSON object.I want to store all the symbol names, high price and low price in separate variables and display those alone in my page in table structure with symbol, high price and low price as columns? How can i do that ? Am able to acces one symbol at a time but i want all the symbols to b displayed ?
Try this: var data = [{ "symbol":"DRREDDY", "series":"EQ", "openPrice":"3,132.00", "highPrice":"3,229.90", "lowPrice":"3,132.00", "ltp":"3,206.35", "previousPrice":"3,153.25", "netPrice":"1.68", "tradedQuantity":"74,165", "turnoverInLakhs":"2,379.33", "lastCorpAnnouncementDate":"18-Jul-2016", "lastCorpAnnouncement":"Annual General Meeting\/ Dividend - Rs 20\/- PerShare" }, ... ]; var table = $('<table>'); table.append('<thead><tr><td>symbol</td><td>highPrice</td><td>lowPrice</td></tr></thead>'); for(var i in data){ var tr = $('<tr>'); var td1 = '<td>' + data[i].symbol; var td2 = '<td>' + data[i].highPrice; var td3 = '<td>' + data[i].lowPrice; tr.append(td1,td2,td3); table.append(tr); } $('#your-panel').append(table); There is Jsfiddle
Iterate list to table var table = document.getElementById("myTable"); for(var i =0; i < data.length; i++) { var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); cell1.innerHTML = data[i].symbol; cell2.innerHTML = data[i].highPrice; cell3.innerHTML = data[i].lowPrice; } fiddle
You may not need to create separate array for symbol, highPrice & lowPrice. Instead you can use forEach to loop through the json array and get each of the item var _tbody = $('tbody'); _myJson.forEach(function(item){ var _tr = '<tr><td>'+item.symbol+'</td><td>'+item.highPrice+'</td><td>'+item.lowPrice+'</td></tr>' _tbody+=_tr }) $('#demoTable').append(_tbody) JSFIDDLE
assuming your objects exist in an array like below var arr = [{ "symbol":"DRREDDY", "series":"EQ", "openPrice":"3,132.00", "highPrice":"3,229.90", "lowPrice":"3,132.00", "ltp":"3,206.35", "previousPrice":"3,153.25", "netPrice":"1.68", "tradedQuantity":"74,165", "turnoverInLakhs":"2,379.33", "lastCorpAnnouncementDate":"18-Jul-2016", "lastCorpAnnouncement":"Annual General Meeting\/ Dividend - Rs 20\/- PerShare" }, { "symbol":"ACC", "series":"EQ", "openPrice":"1,567.00", "highPrice":"1,606.85", "lowPrice":"1,564.85", "ltp":"1,594.25", "previousPrice":"1,568.10", "netPrice":"1.67", "tradedQuantity":"1,03,292", "turnoverInLakhs":"1,645.62", "lastCorpAnnouncementDate":"22-Feb-2016", "lastCorpAnnouncement":"Dividend - Rs 6\/- Per Share" }, { "symbol":"ACC", "series":"EQ", "openPrice":"1,567.00", "highPrice":"1,606.85", "lowPrice":"1,564.85", "ltp":"1,594.25", "previousPrice":"1,568.10", "netPrice":"1.67", "tradedQuantity":"1,03,292", "turnoverInLakhs":"1,645.62", "lastCorpAnnouncementDate":"22-Feb-2016", "lastCorpAnnouncement":"Dividend - Rs 6\/- Per Share" }] you can loop through array to draw rows and loop through objects to draw columns like below var tableData = '' arr.map((x) => { tableData += '<tr><td>' + x.highPrice + '</td><td>' + x.lowPrice + '</td></tr>'; }); $('table').find('tbody').html(tableData)
consider var result= {"symbol":"DRREDDY","series":"EQ","openPrice":"3,132.00","highPrice":"3,229.90","lowPrice":"3,132.00","ltp":"3,206.35","previousPrice":"3,153.25","netPrice":"1.68","tradedQuantity":"74,165","turnoverInLakhs":"2,379.33","lastCorpAnnouncementDate":"18-Jul-2016","lastCorpAnnouncement":"Annual General Meeting\/ Dividend - Rs 20\/- PerShare"}, {"symbol":"ACC","series":"EQ","openPrice":"1,567.00","highPrice":"1,606.85","lowPrice":"1,564.85","ltp":"1,594.25","previousPrice":"1,568.10","netPrice":"1.67","tradedQuantity":"1,03,292","turnoverInLakhs":"1,645.62","lastCorpAnnouncementDate":"22-Feb-2016","lastCorpAnnouncement":"Dividend - Rs 6\/- Per Share"}, {"symbol":"ACC","series":"EQ","openPrice":"1,567.00","highPrice":"1,606.85","lowPrice":"1,564.85","ltp":"1,594.25","previousPrice":"1,568.10","netPrice":"1.67","tradedQuantity":"1,03,292","turnoverInLakhs":"1,645.62","lastCorpAnnouncementDate":"22-Feb-2016","lastCorpAnnouncement":"Dividend - Rs 6\/- Per Share"} var low_price,high_price,symbols=[]; for(var i=0; i<result.length; i++){ low_price[i]=result[i].lowPrice; } to display in table u can use a display function inside the for loop like this .. for(var i=0; i<result.length; i++){ //low_price[i]=result[i].lowPrice; display(result[i]); } function display(result){ var rows='<tr>'+ '<td>'+result.symbol+'</td>'+ '<td>'+result.highPrice+'</td>'+ '<td>'+result.lowPrice+'</td>'+ '</tr>'; $('#result').append(rows); } In html page <div> <table> <thead> <th>Symbols</th> <th>High price</th> <th>Low price</th> </thead> <tbody id="result"> // your display function will be add rows using append function ... </tbody> </table> </div i guess u r looking for this .. otherwise sorry for the wrong information please provide more information that u want
Create html table from comma separated strings 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); }