I need to add rows dynamically to a table on a button click event using JavaScript. In addition, the table cells need to contain textboxes.
How can I do this?
Here's a sample code taken from this source. Suggest you read more about DOM, specifically about DOM tables for this question.
function start() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var j = 0; j < 2; j++) {
// creates a table row
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
Related
im new to coding and try to build a dynamic table.
1st column works fine every new cell goes to top . want to do the same on second 3rd etc.. but when i try to add column to table fills from top to bottom.
i want my table to look like
5|5|5
4|4|4
3|3|3
2|2|2
1|1|1
0|0|0
function createcolumn() {
for (var i = 0; i < 6; i++){
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = "NEW CELL1 - "+i;
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
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
}
function addcolumn() {
var tbl = document.getElementById('myTable'), // table reference
i;
// open loop for each row and append cell
//for (i = 0; i < tbl.rows.length; i++) {
for (i = 5; i < tbl.rows.length; i--) {
createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
}
}
table, td {
border: 1px solid black;
}
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table id="myTable">
</table>
<br>
<button type="button" onclick="createcolumn()">1st column</button>
<button type="button" onclick="addcolumn()">add column</button>
<p id="demo"></p>
With your add column function, you can do 5-i instead of just i, that'll display what you want.
createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), 5-i, 'col');
I am having trouble appending the entire preloaded image array to the table created. This code fills the last column. But I want to fill each cell with each one image per cell.
Where am I going wrong? What am I missing here?
function generate_table() {
//preload Image Array
var preload = ["../../images/Large/bcpot002_r1_c1.jpg", "../../images/Large/bcpot002_r2_c1.jpg", "../../images/Large/bcpot002_r3_c1.jpg","../../images/Large/bcpot002_r4_c1.jpg",
"../../images/Large/bcpot002_r1_c2.jpg", "../../images/Large/bcpot002_r2_c2.jpg", "../../images/Large/bcpot002_r3_c2.jpg","../../images/Large/bcpot002_r4_c2.jpg",
"../../images/Large/bcpot002_r1_c3.jpg", "../../images/Large/bcpot002_r2_c3.jpg", "../../images/Large/bcpot002_r3_c3.jpg","../../images/Large/bcpot002_r4_c3.jpg",
"../../images/Large/bcpot002_r1_c4.jpg", "../../images/Large/bcpot002_r2_c4.jpg", "../../images/Large/bcpot002_r3_c4.jpg","../../images/Large/bcpot002_r4_c4.jpg",
"../../images/Large/bcpot002_r1_c5.jpg", "../../images/Large/bcpot002_r2_c5.jpg", "../../images/Large/bcpot002_r3_c5.jpg","../../images/Large/bcpot002_r4_c5.jpg",];
//preload Images
var images = [];
for (i = 0; i < preload.length; i++) {
images[i] = new Image();
images[i].src = preload[i];
images[i].className="myImg";
}
// get the reference for display div
var imagediv = document.getElementById("test");
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < 4; i++) {
// creates a table row
var row = document.createElement("tr");
row.setAttribute("class", "myTr");
for (var j = 0; j < 5; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
cell.appendChild(images[i]);
cell.setAttribute("class", "myTd");
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
imagediv.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("cellpadding", "0");
tbl.setAttribute("cellspacing", "0");
tbl.setAttribute("class", "myTable");
}
Your images urls are indexed with rows of each cell first while you are accessing it through the row iterator which only returns the first 4 images due to your condition : for (var i = 0; i < 4; i++). So you need to use the second iterator as well to get the respective image :
cell.appendChild(images[(j*4) + i]);
https://jsfiddle.net/mjnxhwkL/
I want to create a bookmarklet by using javascript, which can retrieve max length of all text box in the page, and then print a table below the page with all id and max length indicated.
Here is my code, however it did not print anything.
javascript: (function() {
var body =document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
var tbdy = document.createElement('tbody');
var D = document,
i, f, j, e;
for (i = 0; f = D.forms[i]; ++i)
for (j = 0; e = f[j]; ++j)
if (e.type == "text") S(e);
function S(e) {
var l= document.getElementById(e.id);
var x = document.getElementById(e.maxlength);
var tr=document.createElement('tr');
var td1=document.createElement('td');
var td2=document.createElement('td');
td1.appendChild(document.createTextNode(l));
td2.appendChild(document.createTextNode(x));
tr.appendChild(td1);
tr.appendChild(td2);
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl);
})
This can actually be done much simpler than you have it.
Working jsfiddle: https://jsfiddle.net/cecu3daf/
You want to grab all of the inputs and run a loop over them. From this you can dynamically create a table and append it to the end of the document.body
var inputs = document.getElementsByTagName("input"); //get all inputs
var appTable = document.createElement("table"); //create a table
var header = appTable.createTHead(); //create the thead for appending rows
for (var i=0; i<inputs.length; i++) { //run a loop over the input elements
var row = header.insertRow(0); //insert a row to the table
var cell = row.insertCell(0); //insert a cell into the row
cell.innerHTML = inputs[i].maxLength; //input data into the cell
var cell = row.insertCell(0);
cell.innerHTML = inputs[i].id;
}
document.body.appendChild(appTable); //append the table to the document
To make it a bookmark, simply place the javascript: before hand. There is no need to encase it in a function. You can if you'd like to.
I am doing an exercise (from Beginning Javascript) to better understand DOM manipulation. Attempting to recreate the following table in a DRY method using only JS (the textbook solution is here):
<table>
<tr>
<td>Car</td>
<td>Top Speed</td>
<td>Price</td>
</tr>
<tr>
<td>Chevrolet</td>
<td>120mph</td>
<td>$10,000</td>
</tr>
<tr>
<td>Pontiac</td>
<td>140mph</td>
<td>$20,000</td>
</tr>
</table>
I tried this but unsure how you can loop variable creation without throwing an error:
var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from
var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document
for (var i = 0; i<3; i++) {
var tr[i] = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
table.appendChild(tr[i]); // Append to <table> node
for (var j = 0; j<3; j++) {
var tdText = document.createTextNode(array[i][j]); // Extract data from array to a placeholder variable
tr[i].appendChild(tdText); // Take string from placeholder variable and append it to <tr> node
}
}
As already said the problem is the syntax error in declaring the tr[i] variable.
A more cleaner way will be is to use the table api methods like
var array = [
['Car', 'Top Speed', 'Price'],
['Chevrolet', '120mph', '$10,000'],
['Pontiac', '140pmh', '$20,000']
] // Creating a data array which a loop will source from
var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document
array.forEach(function(row) {
var tr = table.insertRow(); //Create a new row
row.forEach(function(column) {
var td = tr.insertCell();
td.innerText = column; // Take string from placeholder variable and append it to <tr> node
});
});
HTMLTableElement
insertRow()
insertCell
Please use tr instead of tr[i]. It will work
var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from
var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document
for (var i = 0; i<3; i++) {
var tr = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
table.appendChild(tr); // Append to <table> node
for (var j = 0; j<3; j++) {
var tdElement = document.createElement('td');
tdElement.innerHTML = array[i][j];
tr.appendChild(tdElement); // Take string from placeholder variable and append it to <tr> node
}
}
My version with the use of THead and TBody as well as th and td.
// input as an array
const array = [
['Car', 'Top Speed', 'Price'],
['Chevrolet', '120mph', '$10,000'],
['Pontiac', '140pmh', '$20,000']
]
const table = document.createElement('table');
// Generate Header
const head = table.createTHead();
const tr = head.insertRow();
array[0].forEach(function(item) {
const th = document.createElement('th')
th.appendChild(document.createTextNode(item));
tr.appendChild(th);
});
// Generate Body
const body = table.createTBody();
array.slice(1).forEach(function(row) {
const tr = body.insertRow();
row.forEach(function(item, index) {
if (index === 0) {
const th = document.createElement('th')
th.appendChild(document.createTextNode(item));
tr.appendChild(th);
} else {
const td = tr.insertCell(); // create td only
td.appendChild(document.createTextNode(item));
}
});
});
document.body.appendChild(table);
ref:
<thead>: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead
<tbody>: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody
<th>: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th
The individual table rows are giving me a problem. I have created what I want using divs but I need to use a table instead of divs. My table has 220 cells, 10 rows, and 22 columns. Each cell has to have the value of i inside the innerHTML. Here is similar to what i want using Divs ( although the cell height and width does not have to be set ):
<!DOCTYPE html>
<html>
<head>
<style>
#container{
width:682px; height:310px;
background-color:#555; font-size:85%;
}
.cell {
width:30px; height:30px;
background-color:#333; color:#ccc;
float:left; margin-right:1px;
margin-bottom:1px;
}
</style>
</head>
<body>
<div id="container">
<script>
for( var i = 1; i <= 220; i++ ){
document.getElementById( 'container' ).innerHTML +=
'<div class="cell">' + i + '</div>'
}
</script>
</div>
</body>
</html>
http://jsfiddle.net/8r6619wL/
This is my starting attempt using a table:
<script>
for( var i = 0; i <= 10; i++ )
{
document.getElementById( 'table' ).innerHTML +=
'<tr id = "row' + i + '"><td>...</td></tr>';
}
</script>
But that code somehow dynamically creates a bunch of tbody elements. Thanks for help as I newb
You can do this with nested loops - one to add cells to each row and one to add rows to the table. JSFiddle
var table = document.createElement('table'), tr, td, row, cell;
for (row = 0; row < 10; row++) {
tr = document.createElement('tr');
for (cell = 0; cell < 22; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = row * 22 + cell + 1;
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
Alternatively, you can create an empty row of 22 cells, clone it 10 times, and then add the numbers to the cells.
var table = document.createElement('table'),
tr = document.createElement('tr'),
cells, i;
for (i = 0; i < 22; i++) { // Create an empty row
tr.appendChild(document.createElement('td'));
}
for (i = 0; i < 10; i++) { // Add 10 copies of it to the table
table.appendChild(tr.cloneNode(true));
}
cells = table.getElementsByTagName('td'); // get all of the cells
for (i = 0; i < 220; i++) { // number them
cells[i].innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
And a third option: add the cells in a single loop, making a new row every 22 cells.
var table = document.createElement('table'), tr, td, i;
for (i = 0; i < 220; i++) {
if (i % 22 == 0) { // every 22nd cell (including the first)
tr = table.appendChild(document.createElement('tr')); // add a new row
}
td = tr.appendChild(document.createElement('td'));
td.innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
Edit - how I would do this nowadays (2021)... with a helper function of some kind to build dom elements, and using map.
function make(tag, content) {
const el = document.createElement(tag);
content.forEach(c => el.appendChild(c));
return el;
}
document.getElementById("container").appendChild(make(
"table", [...Array(10).keys()].map(row => make(
"tr", [...Array(22).keys()].map(column => make(
"td", [document.createTextNode(row * 22 + column + 1)]
))
))
));
There are a lot of ways to do this, but one I've found to be helpful is to create a fragment then append everything into it. It's fast and limits DOM re-paints/re-flows from a loop.
Take a look at this jsbin example.
Here's the modified code:
function newNode(node, text, styles) {
node.innerHTML = text;
node.className = styles;
return node;
}
var fragment = document.createDocumentFragment(),
container = document.getElementById("container");
for(var i = 1; i <= 10; i++) {
var tr = document.createElement("tr");
var td = newNode(document.createElement("td"), i, "cell");
tr.appendChild(td);
fragment.appendChild(tr);
}
container.appendChild(fragment);
You can modify whatever you want inside the loop, but this should get you started.
That's because the DOM magically wraps a <tbody> element around stray table rows in your table, as it is designed to do. Fortunately, you can rewrite your loop in a way that will add all of those table rows at once, rather than one at a time.
The simplest solution to achieve this would be to store a string variable, and concatenate your rows onto that. Then, after you've concatenated your rows together into one string, you can set the innerHTML of your table element to that one string like so:
<script>
(function() {
var rows = '';
for( var i = 0; i <= 10; i++ )
{
rows += '<tr id = "row' + i + '"><td>...</td></tr>';
}
document.getElementById( 'table' ).innerHTML = rows;
}());
</script>
Here's a JSFiddle that demonstrates what I've just written. If you inspect the HTML using your browser's developer tools, you'll notice that one (and only one) tbody wraps around all of your table rows.
Also, if you're wondering, the odd-looking function which wraps around that code is simply a fancy way of keeping the variables you've created from becoming global (because they don't need to be). See this blog post for more details on how that works.
please check this out.
This is a very simple way to create a table using js and HTML
<body>
<table cellspacing="5" >
<thead>
<tr>
<td>Particulate count</td>
<td>Temperature</td>
<td>Humidity</td>
</tr>
</thead>
<tbody id="xxx">
</tbody>
</table>
<script>
for (var a=0; a < 2; a++) {
var table1 = document.getElementById('xxx');
var rowrow = document.createElement('tr');
for ( i=0; i <1; i++) {
var cell1 = document.createElement('td');
var text1 = document.createTextNode('test1'+a);
var cell2 = document.createElement('td');
var text2 = document.createTextNode('test2'+a);
var cell3 = document.createElement('td');
var text3 = document.createTextNode('test3'+a);
cell1.appendChild(text1);
rowrow.appendChild(cell1);
cell2.appendChild(text2);
rowrow.appendChild(cell2);
cell3.appendChild(text3);
rowrow.appendChild(cell3);
}
table1.appendChild(rowrow);
}
</script>
</body>
</html>