You could iterate the array and build a new row if the remainder with 5 is zero.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
tr;
array.forEach((v, i) => {
var td = document.createElement('td');
if (!(i % 5)) {
tr = document.createElement('tr');
document.getElementById('table0').appendChild(tr);
}
td.appendChild(document.createTextNode(v));
tr.appendChild(td);
});
<table id="table0"></table>
Answer from Nina Scholz on Stack OverflowYou could iterate the array and build a new row if the remainder with 5 is zero.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
tr;
array.forEach((v, i) => {
var td = document.createElement('td');
if (!(i % 5)) {
tr = document.createElement('tr');
document.getElementById('table0').appendChild(tr);
}
td.appendChild(document.createTextNode(v));
tr.appendChild(td);
});
<table id="table0"></table>
var array = [1,2,3,4,5,6,7,8,9,10];
var result = "<table border=1>";
result += "<tr>";
for (var j = 0; j < array.length; j++) {
result += "<td>" + array[j] + "</td>";
if ((j + 1) % 5 == 0) {
result += "</tr><tr>";
}
}
result += "</tr>";
result += "</table>";
document.body.innerHTML = result;
Please give it a try if that works
Videos
var arr = ["1","2","-3","4","-5","-6","7"];
var table = document.createElement("table"), // create the table element
tbody = document.createElement("tbody"); // create the table body element
table.appendChild(tbody); // add the table body to table
// ### POSITIVE ROW ######################
var tr = document.createElement("tr"); // create the table row element
arr.forEach(function(e) { // for each element e in arr
var td = document.createElement("td"); // create a table cell element
if(e >= 0) { // if e is positive
td.textContent = e; // then change the text content of this cell to e
td.style.background = "#ccc"; // and change the background as well
}
tr.appendChild(td); // add the cell to the row (if the number is negative the cell will be empty and without background)
});
tbody.appendChild(tr); // add the row to table
//### NEGATIVE ROW ######################
tr = document.createElement("tr"); // same but for negative numbers ...
arr.forEach(function(e) {
var td = document.createElement("td");
if(e < 0) {
td.textContent = e;
td.style.background = "#ccc";
}
tr.appendChild(td);
});
tbody.appendChild(tr);
document.body.appendChild(table);
You can group some of the code in a function and reuse it:
// elt is shortcut for document.createElement
function elt(tag) {
return document.createElement(tag);
}
// take an array and a condition function conditionFN and return a row of all the element that passed the condition function with a background of #ccc
function makeRow(arr, conditionFN) {
var tr = elt("tr");
arr.forEach(function(e) {
var td = elt("td");
if (conditionFN(e)) {
td.textContent = e;
td.style.background = "#ccc";
}
tr.appendChild(td);
});
return tr;
}
// take an array and return the equivalent table element
function makeTable(arr) {
var table = elt("table"),
tbody = elt("tbody");
table.appendChild(tbody);
tbody.appendChild(makeRow(arr, function(e) { return e >= 0; })); // the condition function only allows positive numbers => positive row
tbody.appendChild(makeRow(arr, function(e) { return e < 0; })); // the condition function only allows negative numbers => negative row
return table;
}
document.body.appendChild(makeTable([1, 2, -3, 4, -5, -6, -7, 8, 9, 10]));
Using recursive function and table.inertRow() and row.insertCell()
var data = ["1", "2", "-3", "4", "-5", "-6", "7"];
var table = document.getElementById('myTable')
function plusMinusRows(arr, rowNum) {
var row = table.insertRow();
arr.map(Number).forEach(function(num) {
var value = !rowNum ? (num >= 0 ? num : '') : (num < 0 ? num : '');
var cell = row.insertCell();
cell.textContent = value;
cell.style.background = value !== '' ? '#cccccc' : '';
});
// call function again when rowNum not defined
!rowNum && plusMinusRows(arr, 2);
}
// initialize 2 rows
plusMinusRows(data);
<table id="myTable"></table>
You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:
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);
It is because you're only creating two td elements and 2 text nodes.
Creating all nodes in a loop
Recreate the nodes inside your loop:
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);
Creating then cloning in a loop
Create them beforehand, and clone them inside the loop:
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);
Table factory with text string
Make a table factory:
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;
}
And use it like this:
document.getElementById('tablearea')
.appendChild( populateTable(null, 3, 2, "Text") );
Table factory with text string or callback
The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.
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;
}
Used like this:
document.getElementById('tablearea')
.appendChild(populateTable(null, 3, 2, function(t, r, c) {
return ' row: ' + r + ', cell: ' + c;
})
);
Here's a function that will use the dom instead of string concatenation.
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);
This is pretty easy to do with a double for loop.
function makeTableHTML(myArray) {
var result = "<table border=1>";
for(var i=0; i<myArray.length; i++) {
result += "<tr>";
for(var j=0; j<myArray[i].length; j++){
result += "<td>"+myArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
return result;
}
1) This my answer how do this on VueJS and jQuery
2) Vanilla js - CODEPEN - DEMO
// Get DOM elements
const $el = [
'#tmpl',
'#user-count',
'#people-count',
'#form-items',
'#btn-add',
'#form',
].reduce((res, item) => {
const method = item.startsWith('#')
? 'querySelector'
: 'querySelectorAll'
const key = item
.replace(/\W/ig, ' ').trim()
.replace(/\s+\w/g, v => v.trim().toUpperCase())
res[key] = documentmethod
return res
}, {})
// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()
// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
const peopleCount = +$el.peopleCount.value
const html = Array(peopleCount)
.fill(tmpl)
.join('')
$el.formItems.insertAdjacentHTML('beforeend', html)
})
// Submit form
$el.form.addEventListener('submit', e => {
e.preventDefault()
alert('Submit form by ajax or remove this method for default behavior')
})
// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
// Delete behaviors
if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
e.target.closest('.row').remove()
}
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
I have edited your code,
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementsByTagName("tr");
var obj = [];
for(var i=0;i<cellData.length-1;i++){
obj.push(document.getElementById("i"+i).value);
obj.push(document.getElementById("o"+i).value);
}
alert(JSON.stringify(obj));
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>