Reputation: 167
I have array values like this. I want to display these values in HTML table tag
<script type="text/javascript">
var orderArray = [
["1","29-Aug-2012", "Product1", "client1"],
["2","29-Aug-2012", "Product2", "client2"],
["3","29-Aug-2012", "Product3", "client3"],
["4","29-Aug-2012", "Product4", "client4"],
["5","29-Aug-2012", "Product5", "client5"]
];
function display()
{
for(i=0;i<ordertArray.length;i++)
{
//How to display values of array inside the div or table tag ???
}
}
</script>
How to display values of array inside the div or table tag ???
Upvotes: 3
Views: 33960
Reputation: 664217
Use the DOM functions of table elements:
function display() {
var table = document.createElement("table");
for (var i=0; i<orderArray.length; i++) {
var row = table.insertRow();
for (var j=0; j<orderArray[i].length; j++) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(orderArray[i][j]));
}
}
return table;
}
Call that function when the DOM is ready, and append the returned table somewhere.
Upvotes: 2
Reputation: 154818
orderArray
's items represent <tr>
elements, and each item inside represents a <td>
element. So you can loop through orderArray
creating <tr>
s, and then loop through its elements on each loop creating <td>
s: http://jsfiddle.net/h7F7e/.
var table = document.getElementById("table"); // set this to your table
var tbody = document.createElement("tbody");
table.appendChild(tbody);
orderArray.forEach(function(items) {
var row = document.createElement("tr");
items.forEach(function(item) {
var cell = document.createElement("td");
cell.textContent = item;
row.appendChild(cell);
});
tbody.appendChild(row);
});
Upvotes: 6
Reputation: 38147
Something like this would create a dynamic table for you :
// get handle on div
var container = document.getElementById('container');
// create table element
var table = document.createElement('table');
var tbody = document.createElement('tbody');
// loop array
for (i = 0; i < orderArray.length; i++) {
// get inner array
var vals = orderArray[i];
// create tr element
var row = document.createElement('tr');
// loop inner array
for (var b = 0; b < vals.length; b++) {
// create td element
var cell = document.createElement('td');
// set text
cell.textContent = vals[b];
// append td to tr
row.appendChild(cell);
}
//append tr to tbody
tbody.appendChild(row);
}
// append tbody to table
table.appendChild(tbody);
// append table to container
container.appendChild(table);
Uses document.createElement()
and element.appendChild()
Upvotes: 2
Reputation: 4778
var table = "<table>"; // Open Table
for(i=0; i<orderArray.length; i++)
{
table += "<tr>"; // Open Row
for(i2=0; i2<orderArray[i].length; i2++) {
{
table += "<td>" + orderArray[i][i2] + "</td>"; // Each Column
}
table += "</tr>"; // Close Row
}
table += "</table>"; // Close Table
Upvotes: 1