html dynamic table values - javascript

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');

Related

Append IMG to Table

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/

Returning Id of cell when clicked Javascript

I'm working on creating a table of cells that will change color when each cell is clicked on.
I've created the table and have unique Ids for 'td' element - how do I return the Id of the cell that was clicked so that I can change its background color?
Is it possible to do this with pure JS?
const grid = function makeGrid() {
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
var tblBody = document.createElement('tbody');
for (let i = 0; i < 5; i++) {
let row = document.createElement('tr');
for (j = 0; j < 5; j++) {
var cell = document.createElement('td')
row.appendChild(cell)
cell.setAttribute('id', 'makeId' + i + j);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl)
}
grid();
Rather than set event listeners on every single td element, use event delegation.
Set a listener on the table body. It will hear the clicks on the td elements. Use the event object's target property to determine which td was clicked. That is the one the change:
document.querySelector('tbody').addEventListener('click', (e)=>{
e.target.style.backgroundColor = 'pink';
}
You need to bind the click event to the created cell
EDITED: using Event delegation
tblBody.addEventListener('click', (e)=>{
if (e.target.nodeName.toUpperCase() === 'TD') {
console.log(e.target.id)
e.target.classList.add('bg');
}
});
const grid = function makeGrid() {
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table')
var tblBody = document.createElement('tbody')
tblBody.addEventListener('click', (e)=>{
if (e.target.nodeName.toUpperCase() === 'TD') {
console.log(e.target.id)
e.target.classList.add('bg');
}
});
for (let i = 0; i < 5; i++) {
let row = document.createElement('tr')
for (let j = 0; j < 5; j++) {
var cell = document.createElement('td')
cell.innerHTML = 'makeId' + i + j;
row.appendChild(cell)
cell.setAttribute('id', 'makeId' + i + j);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl)
}
grid();
.bg {
background-color: lightgreen;
}
<div id="pixelCanvas">
</div>
As suggested by Randy, rather than put a listener on every TD you can use event delegation and put the listener on a suitable ancestor, either a parent table section (tbody, thead, tfoot) or the table itself. Then use the event object passed to the listener to get the target of the event. If it's not a TD, go up the parent nodes until you reach a TD.
There is now Element.closest implemented in most browsers in use, but not IE. So you might want to use a polyfill or simple "upTo" function for those users.
Also, you can take advantage of the insertRow and insertCell methods of table and table section elements rather than the more long winded createElement. Lastly, you can combine creating the element and appending it in one go.
Anyhow, like this:
// Create a table with rows rows and cells columns
function genTable(rows, cells) {
var table = document.createElement('table');
// Create tbody and append in one go
var tbody = table.appendChild(document.createElement('tbody'));
tbody.addEventListener('click',highlightCell);
var row, cell;
// Use insert methods for less code
for (var i=0; i<rows; i++) {
row = tbody.insertRow();
for (var j=0; j<cells; j++) {
cell = row.insertCell();
cell.textContent = 'row ' + i + ' cell ' + j;
}
}
// Add entire table to document in one go, easier on host
document.body.appendChild(table);
}
// Highlight cell that was clicked on
function highlightCell(e){
// Remove highlight from all cells that have it
document.querySelectorAll('.highlight').forEach(
node => node.classList.remove('highlight')
);
// Add highlight to cell of td in which event occurred
var cell = e.target.closest('td');
cell.classList.add('highlight');
}
window.onload = function(){genTable(3, 3);};
table {
border-collapse: collapse;
border-left: 1px solid #bbbbbb;
border-top: 1px solid #bbbbbb;
}
td {
border-right: 1px solid #bbbbbb;
border-bottom: 1px solid #bbbbbb;
}
.highlight {
background-color: red;
}

Create a bookmarklet that can retrieve all max length of text box and then print the id and max length in a table

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.

How to create a table using a loop?

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>

Dynamically building table using Javascript

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");
}

Categories

Resources