Reputation: 169
I am trying to insert rows into an html table with javascript. I have the table created and can add rows successfully with the click of a button. However, I want to be able to populate the rows with elements from several arrays on load. The button is just to make sure the rows are being added.
<html>
<input type="button" value="Add row" onclick="javascript:appendRow()" class="append_row"/>
<br/><br/></p>
<table id="my_table" align="center" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
</table>
<p></center></p>
<script type="text/javascript" language="javascript">
function appendRow(){
var names = ["Paul", "Mike", "Linda"];
var ages = ["16", "23", "44"];
var male_female = ["M", "M", "F"];
var tbl = document.getElementById('my_table'); // table reference
// append table row
var row = tbl.insertRow(tbl.rows.length);
// insert table cells to the new row
var row = tbl.insertRow();
for(var i=0;i<tbl.rows[0].cells.length;i++)
createCell(row.insertCell(i), i, 'row');
}
function createCell(cell, text, style){
var div = document.createElement('div'); // create DIV element
var txt = document.createTextNode(text); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('class', style); // set DIV class attribute
div.setAttribute('className', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
</script>
<style>
.row{background-color:#FFD6D6;width:43px;margin:3px;}
.col{background-color:#D6FFD6;width:43px;margin:3px;}
table#my_table{border-collapse:collapse;}
table#my_table td{width:50px;height:27px;border:1px solid #D3D3D3;font- size:10pt;text-align:center;padding:0;}
.append_row{background-color:#FFD6D6;border:1px #ccc solid;}
.append_column{background-color:#D6FFD6;border:1px #ccc solid;}
.delete{background-color:#eee;border:1px #ccc solid;}
</style>
</html>
Upvotes: 2
Views: 3764
Reputation: 6255
In your for loop, try something like:
var j = tbl.rows.length - 1;
for (var i=0;i<tbl.rows[0].cells.length;i++) {
var cell_text = '';
if (i == 0) {
cell_text = name[j];
} else if (i == 1) {
cell_text = ages[j];
} else if (i == 2) {
cell_text = male_female[j];
}
createCell(row.insertCell(i), cell_text, 'row');
}
Upvotes: 3
Reputation: 2807
You forgot the "body" tag in the HTML syntax. You can put a call to your function in the onLoad variable, so it will be called after the page with loaded.
Upvotes: 1