Populate Html Table From Javascript Array Format
Suppose i have an java script Array in the following format, [ 'Heading 1', 'Heading 2', 'Data 1', 'Data 2', 'Data 3', 'Data 4', ] I need to make a HTML table from the array in t
Solution 1:
Here you can find some code to make what you need to:
//set the number of columns (we use 2 because you have 2 "Heading")var _numberCol = 2,
_arr = [
"Heading 1",
"Heading 2",
"Data 1",
"Data 2",
"Data 3",
"Data 4"
];
//create a tablevar $table = document.createElement("table"), $row;
for(var _k = 0; _k < _arr.length; _k++){
//we create a row when index is divisible for _numberColif(_k % _numberCol===0) $row = $table.insertRow(-1);
//for each element inside the array we crate a cell inside the current row
$col = $row.insertCell(-1);
//then we put the value inside like text
$col.innerText = _arr[_k];
}
//now we can append our table where we need to place itdocument.body.appendChild($table);
This code works only with your type of array that has only one dimension, and all Heading are defined like each other cell in the table.
Solution 2:
If you need it in JS you can use the array to create an html string for the table. If you then need to put it inside an element in your html page you could do something like:
document.getElementById("myDiv").innerHTML = myHtmlTable;
I wrote an example of a function to generate such a string in this JSfiddle.
(Let me know if you can't access the fiddle, I've never used it before for StackOverflow answers).
Solution 3:
var data = [
"Heading 1",
"Heading 2",
"Data 1",
"Data 2",
"Data 3",
"Data 4",
]
var tabdiv = document.createElement('div');
tabdiv.setAttribute("id", "tab");
document.body.appendChild(tabdiv)
document.getElementById("tab").innerHTML = "<table border = '1' style='border-collapse: collapse;'>" +'<tr>' + '<th>'+ data[0] + "</th>" + '<th>'+ data[1] + "</th>" + '</tr>' + '<tr>' + '<td>' + data[2] + '</td>' + '<td>' + data[3] + '</td>' + '</tr>' + '<td>' + data[4] + '</td>' + '<td>' + data[5] + '</td>' + '</tr>';
Post a Comment for "Populate Html Table From Javascript Array Format"