J'essaie d'insérer des lignes dans une table html avec javascript. J'ai créé la table et peut ajouter des lignes avec succès en cliquant sur un bouton. Cependant, je veux pouvoir remplir les lignes avec des éléments de plusieurs tableaux en charge. Le bouton est juste pour s'assurer que les lignes sont ajoutées.Ajout de lignes dans le tableau HTML en utilisant javascript
<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>
re l'appel 'de setAttribute' et IE bidouille: ne pas utiliser setAttribute'' getAttribute'/'dans un document HTML, pour cette raison. Mieux vaut s'en tenir aux propriétés HTML DOM niveau 1 comme 'div.className = style'. – bobince