Creación dinámica de tabla con DOM

¿Puede alguien decirme qué pasa con este código? Quiero crear una tabla con 2 columnas y 3 filas, y en las celdas quiero Text1 y Text2 en cada fila. Este código crea una tabla con 2 columnas y 3 filas, pero solo es text en las celdas de la tercera fila (las otras están vacías).

var tablearea = document.getElementById('tablearea'); var table = document.createElement('table'); var tr = []; var td1 = document.createElement('td'); var td2 = document.createElement('td'); var text1 = document.createTextNode('Text1'); var text2 = document.createTextNode('Text2'); for (var i = 1; i < 4; i++){ tr[i] = document.createElement('tr'); for (var j = 1; j < 4; j++){ td1.appendChild(text1); td2.appendChild(text2); tr[i].appendChild(td1); tr[i].appendChild(td2); } table.appendChild(tr[i]); } tablearea.appendChild(table); 

Debe crear nodos de td y de text dentro del ciclo. Tu código crea solo 2 td, por lo que solo 2 son visibles. Ejemplo:

 var table = document.createElement('table'); for (var i = 1; i < 4; i++){ var tr = document.createElement('tr'); var td1 = document.createElement('td'); var td2 = document.createElement('td'); var text1 = document.createTextNode('Text1'); var text2 = document.createTextNode('Text2'); td1.appendChild(text1); td2.appendChild(text2); tr.appendChild(td1); tr.appendChild(td2); table.appendChild(tr); } document.body.appendChild(table); 

Es porque solo está creando dos elementos td y 2 nodos de text.


Crear todos los nodos en un bucle

Recrea los nodos dentro de tu ciclo:

 var tablearea = document.getElementById('tablearea'), table = document.createElement('table'); for (var i = 1; i < 4; i++) { var tr = document.createElement('tr'); tr.appendChild( document.createElement('td') ); tr.appendChild( document.createElement('td') ); tr.cells[0].appendChild( document.createTextNode('Text1') ) tr.cells[1].appendChild( document.createTextNode('Text2') ); table.appendChild(tr); } tablearea.appendChild(table); 

Creando luego la clonación en un bucle

Créelos de antemano y clonelos dentro del ciclo:

 var tablearea = document.getElementById('tablearea'), table = document.createElement('table'), tr = document.createElement('tr'); tr.appendChild( document.createElement('td') ); tr.appendChild( document.createElement('td') ); tr.cells[0].appendChild( document.createTextNode('Text1') ) tr.cells[1].appendChild( document.createTextNode('Text2') ); for (var i = 1; i < 4; i++) { table.appendChild(tr.cloneNode( true )); } tablearea.appendChild(table); 

Fábrica de tables con cadena de text

Hacer una fábrica de table:

 function populateTable(table, rows, cells, content) { if (!table) table = document.createElement('table'); for (var i = 0; i < rows; ++i) { var row = document.createElement('tr'); for (var j = 0; j < cells; ++j) { row.appendChild(document.createElement('td')); row.cells[j].appendChild(document.createTextNode(content + (j + 1))); } table.appendChild(row); } return table; } 

Y úsalo así:

 document.getElementById('tablearea') .appendChild( populateTable(null, 3, 2, "Text") ); 

Fábrica de tablas con cadena de text o callback

La fábrica podría modificarse fácilmente para aceptar también una function para el cuarto argumento a fin de poblar el contenido de cada celda de una manera más dinámica.

 function populateTable(table, rows, cells, content) { var is_func = (typeof content === 'function'); if (!table) table = document.createElement('table'); for (var i = 0; i < rows; ++i) { var row = document.createElement('tr'); for (var j = 0; j < cells; ++j) { row.appendChild(document.createElement('td')); var text = !is_func ? (content + '') : content(table, i, j); row.cells[j].appendChild(document.createTextNode(text)); } table.appendChild(row); } return table; } 

Usado así:

 document.getElementById('tablearea') .appendChild(populateTable(null, 3, 2, function(t, r, c) { return ' row: ' + r + ', cell: ' + c; }) ); 

Necesita crear nuevos TextNodes así como nodos td para cada columna, no reutilizarlos entre todas las columnas como lo hace su código.

Editar: revise su código así:

 for (var i = 1; i < 4; i++) { tr[i] = document.createElement('tr'); var td1 = document.createElement('td'); var td2 = document.createElement('td'); td1.appendChild(document.createTextNode('Text1')); td2.appendChild(document.createTextNode('Text2')); tr[i].appendChild(td1); tr[i].appendChild(td2); table.appendChild(tr[i]); } 

cuando dices 'appendchild', en realidad mueves a tu hijo de un padre a otro. tienes que crear un nodo para cada celda.

 <title>Registration Form</title> <script> var table; function check() { debugger; var name = document.myForm.name.value; if (name == "" || name == null) { document.getElementById("span1").innerHTML = "Please enter the Name"; document.myform.name.focus(); document.getElementById("name").style.border = "2px solid networking"; return false; } else { document.getElementById("span1").innerHTML = ""; document.getElementById("name").style.border = "2px solid green"; } var age = document.myForm.age.value; var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm; if (age == "" || age == null) { document.getElementById("span2").innerHTML = "Please provide Age"; document.myForm.age.focus(); document.getElementById("age").style.border = "2px solid networking"; return false; } else if (!ageFormat.test(age)) { document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60"; document.myForm.age.focus(); document.getElementById("age").style.border = "2px solid networking"; return false; } else { document.getElementById("span2").innerHTML = ""; document.getElementById("age").style.border = "2px solid green"; } var password = document.myForm.password.value; if (document.myForm.password.length < 6) { alert("Error: Password must contain at least six characters!"); document.myForm.password.focus(); document.getElementById("password").style.border = "2px solid networking"; return false; } re = /[0-9]/g; if (!re.test(password)) { alert("Error: password must contain at least one number (0-9)!"); document.myForm.password.focus(); document.getElementById("password").style.border = "2px solid networking"; return false; } re = /[az]/g; if (!re.test(password)) { alert("Error: password must contain at least one lowercase letter (az)!"); document.myForm.password.focus(); document.getElementById("password").style.border = "2px solid networking"; return false; } re = /[AZ]/g; if (!re.test(password)) { alert("Error: password must contain at least one uppercase letter (AZ)!"); document.myForm.password.focus(); document.getElementById("password").style.border = "2px solid networking"; return false; } re = /[$&+,:;=?@#|'<>.^*()%!-]/g; if (!re.test(password)) { alert("Error: password must contain at least one special character!"); document.myForm.password.focus(); document.getElementById("password").style.border = "2px solid networking"; return false; } else { document.getElementById("span3").innerHTML = ""; document.getElementById("password").style.border = "2px solid green"; } if (document.getElementById("data") == null) createTable(); else { appendRow(); } return true; } function createTable() { var myTableDiv = document.getElementById("myTable"); //indiv table = document.createElement("TABLE"); //TABLE?? table.setAttribute("id", "data"); table.border = '1'; myTableDiv.appendChild(table); //appendChild() insert it in the document (table --> myTableDiv) debugger; var header = table.createTHead(); var th0 = table.tHead.appendChild(document.createElement("th")); th0.innerHTML = "Name"; var th1 = table.tHead.appendChild(document.createElement("th")); th1.innerHTML = "Age"; appendRow(); } function appendRow() { var name = document.myForm.name.value; var age = document.myForm.age.value; var rowCount = table.rows.length; var row = table.insertRow(rowCount); row.insertCell(0).innerHTML = name; row.insertCell(1).innerHTML = age; clearForm(); } function clearForm() { debugger; document.myForm.name.value = ""; document.myForm.password.value = ""; document.myForm.age.value = ""; } function restrictCharacters(evt) { evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) { return true; } else { return false; } } </script> <div> <form name="myForm"> <table id="tableid"> <tr> <th>Name</th> <td> <input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td> <td><span id="span1"></span></td> </tr> <tr> <th>Age</th> <td> <input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age" name="age" id="age" /></td> <td><span id="span2"></span></td> </tr> <tr> <th>Password</th> <td> <input type="password" name="password" id="password" placeholder="Password" /></td> <td><span id="span3"></span></td> </tr> <tr> <td></td> <td> <input type="button" value="Submit" onclick="check();" /></td> <td> <input type="reset" name="Reset" /></td> </tr> </table> </form> <div id="myTable"> </div> </div> 

En mi ejemplo, el número de serie se gestiona de acuerdo con las acciones tomadas en cada fila usando css. Usé un formulario dentro de cada fila, y cuando se creó una nueva fila, el formulario se restablecerá.

 /*auto increment/decrement the sr.no.*/ body { counter-reset: section; } i.srno { counter-reset: subsection; } i.srno:before { counter-increment: section; content: counter(section); } /****/ 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type='text/javascript'> $(document).ready(function () { $('#POITable').on('change', 'select.search_type', function (e) { var selectedval = $(this).val(); $(this).closest('td').next().html(selectedval); }); }); </script> <table id="POITable" border="1"> <tr> <th>Sl No</th> <th>Name</th> <th>Your Name</th> <th>Number</th> <th>Input</th> <th>Chars</th> <th>Action</th> </tr> <tr> <td><i class="srno"></i></td> <td> <select class="search_type" name="select_one"> <option value="">Select</option> <option value="abc">abc</option> <option value="def">def</option> <option value="xyz">xyz</option> </select> </td> <td></td> <td> <select name="select_two" > <option value="">Select</option> <option value="123">123</option> <option value="456">456</option> <option value="789">789</option> </select> </td> <td><input type="text" size="8"/></td> <td> <select name="search_three[]" > <option value="">Select</option> <option value="one">1</option> <option value="two">2</option> <option value="three">3</option> </select> </td> <td><button type="button" onclick="deleteRow(this)">-</button><button type="button" onclick="insRow()">+</button></td> </tr> </table> <script type='text/javascript'> function deleteRow(row) { var i = row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i); } function insRow() { var x = document.getElementById('POITable'); var new_row = x.rows[1].cloneNode(true); var len = x.rows.length; //new_row.cells[0].innerHTML = len; //auto increment the srno var inp1 = new_row.cells[1].getElementsByTagName('select')[0]; inp1.id += len; inp1.value = ''; new_row.cells[2].innerHTML = ''; new_row.cells[4].getElementsByTagName('input')[0].value = ""; x.appendChild(new_row); } </script> 
 var html = ""; for (var i = 0; i < data.length; i++){ html +="<tr>"+ "<td>"+ (i+1) + "</td>"+ "<td>"+ data[i].name + "</td>"+ "<td>"+ data[i].number + "</td>"+ "<td>"+ data[i].city + "</td>"+ "<td>"+ data[i].hobby + "</td>"+ "<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>"; } $("#tableHtml").html(html);