How to make the middle Column to be X rather than 0.
Here is my code:
var table = document.createElement('table'), tr, td, row, cell;
for (row = 0; row < 3; row++) {
tr = document.createElement('tr');
for (cell = 0; cell < 3; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = 0
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
<div id="container"></div>
You could add a check if the cell is 1. Then take an 'X'.
var table = document.createElement('table'),
tr, td, row, cell;
for (row = 0; row < 3; row++) {
tr = document.createElement('tr');
for (cell = 0; cell < 3; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = cell === 1 ? 'X' : 0;
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
<div id="container">
</div>
One option is to use switch:
var table = document.createElement('table');
for (var row = 0; row < 3; row++) {
var tr = document.createElement('tr');
for (var cell = 0; cell < 3; cell++) {
var td = document.createElement('td');
//console.log(cell);
var cellText = "";
// This switch picks content based on cell order
switch(cell) {
case 0: cellText = "0"; break;
case 1: cellText = "X"; break;
case 2: cellText = "0"; break;
// Default value if cell count changes
default: cellText = "Unknown cell!";
}
// Using `new Text` ensures the value is entered as text, not HTML
// This can protect you from XSS or unexpected behavior
td.appendChild(new Text(cellText));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
<div id="container">
</div>
It's not the most maintainable solution, but good enough for simple script.
Related
I want to type text inside the cell but I tried to set attribute with td but it doesn't work. Please help me how can I set attribute to type text in the cell. Thank you for your help!
function addTable() {
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
You need to create an input element and then append that to td:
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns", 1);
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('value', 'text');
td.appendChild(input);
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
<div id="myDynamicTable">
</div>
You can use contenteditable attribute: td.contenteditable = 'true';.
Depending on how you want to use this value, you might also insert an input element.
You are perhaps looking for contentEditable?
function addTable() {
const rn = +window.prompt("Input number of rows", 1);
const cn = +window.prompt("Input number of columns", 1);
const myTableDiv = document.getElementById("myDynamicTable");
const table = document.createElement('table');
table.border = '1';
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);
for (let i = 0; i < rn; i++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (let j = 0; j < cn; j++) {
var td = document.createElement('td');
td.width = '75';
td.contentEditable = true;
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
<div id="myDynamicTable"></div>
if you want to operate on tables, use corrects javascript instructions ...
const
DynTb = document.getElementById('myDynamicTable')
rn = +window.prompt("Input number of rows", 1)
, cn = +window.prompt("Input number of columns", 1)
;
if( isNaN(rn) || isNaN(cn))
throw 'bad integer input value (s)'
const myTable = addTable(DynTb, rn, cn )
function addTable(tDiv, rn, cn)
{
let
tab = tDiv.appendChild( document.createElement('table') )
, tBy = tab.createTBody()
;
for(let r=0;r<rn;++r)
{
let row = tBy.insertRow()
for(let c=0;c<cn;++c)
{
row.insertCell().innerHTML =
`<input type="text" placeHolder="${r}-${c}">`
} }
return tab
}
table {
border-collapse : collapse;
margin : 2em 1em;
}
td {
padding : .2em;
border : 1px solid darkblue;
}
input {
width : 5em;
}
<div id="myDynamicTable"></div>
I tried to create table but I can't create td in every tr, td is creating only in first td what is in table, how I can solve the problem?
// Creating div
var main = document.createElement("div")
main.innerHTML = ""
document.body.appendChild(main)
main.setAttribute("id", "main")
//Creating Icons
var puzzleico = document.createElement("div")
puzzleico.innerHTML = ""
document.getElementById("main").appendChild(puzzleico)
puzzleico.setAttribute("id", "puzzleico")
var puzzleico = document.getElementById("puzzleico").onclick = function() {createtable()};
//Creating tr and td
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr")
var td = document.createElement("td")
td.innerHTML = ""
document.getElementById("tr").appendChild(td)
}
}
Element id's within a document need to be unique. The issue here is that your document.getElementById("tr") will always return the first element it finds with that id and so, all of your <td> elements will be appended to the first <tr>.
In order to fix it you can remove the tr.setAttribute("id", "tr") line and use the already existing tr variable to append the td child to.
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr);
var td = document.createElement("td");
td.innerHTML = "test"
tr.appendChild(td)
}
}
createtable();
The above code will work, but using the already declared variables instead of finding them again can also be applied to the table case. Also, table.innerHTML = "" doesn't add any value because the innerHTML is already empty when you create a new element.
function createtable() {
//Creating Table
var table = document.createElement("table");
document.body.appendChild(table);
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr");
table.appendChild(tr);
var td = document.createElement("td");
td.innerHTML = "test";
tr.appendChild(td);
}
}
You can use this to create the table:
function createTable(){
//Creating And Appending Child
let table = document.createElement('table');
document.body.appendChild(table);
for(let i = 0; i < 50; i++){
let tr = document.createElement('tr');
let td = document.createElement('td');
td.innerHTML = i;
tr.appendChild(td);
table.appendChild(tr);
}
}
Here is the link to my codepen:
https://codepen.io/prabodhpanda/pen/gOPLqYe?editors=1010
id attribute of each element in DOM should be unique. You set same id for each tr element you create. document.getElementById element always returns the first element match by the id. This is the reason of the issue. Your last code snippet should be:
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr" + i) // Check this
var td = document.createElement("td")
td.innerHTML = ""
document.getElementById("tr" + i).appendChild(td) // Check this
}
}
tr.appendChild(td) should also work if you don't need ID attribute.
I edited your answer and got what I want.
//Creating tr and td
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr")
for (var v = 0; v < 50; v++) {
var td = document.createElement("td")
td.innerHTML = ""
tr.appendChild(td)
}
}
}
I want to rotate the values in HTML table rows with button, but in the following code "Move" button is not working. Display button will give following table:
0 1 2
0 1 2
0 1 2
by clicking on move button I want table as follows:
2 0 1
2 0 1
2 0 1
and keep rotating the values in row by clicking the move button
<body>
<script>
var myArray = new Array();
var i=0;
var j=0;
function display()
{
var table = document.createElement('table');
table.setAttribute("id", "tbl");
for (i = 0; i < 4; i++){
var tr = document.createElement('tr');
for (j = 0; j < 4; j++)
{
var td= document.createElement('td');
var text = document.createTextNode(j);
td.appendChild(text);
tr.appendChild(td);
table.appendChild(tr);
document.body.appendChild(table);
}
}
}
function move()
{
var table = document.getElementById('tbl');
for(i=0;i<4;i++)
{
var x = table.rows[i].cells[9].innerHTML;
for(j=0;j<4;j++)
{
table.rows[i].cells[j+1].innerHTML = table.rows[i].cells[j].innerHTML;
}
table.rows[i].cells[0].innerHTML=x;
}
}
</script>
HTML:
<input id="display" type="button" value="Display" onclick="display();" />
<input id="move" type="button" value="Move" onclick="move();" />
maybe:
function display() {
var table = document.createElement('table');
table.setAttribute("id", "tbl");
for (var i = 0; i < 4; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 4; j++) {
var td = document.createElement('td');
var text = document.createTextNode(j);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
function move() {
var table = document.querySelector('#tbl');
var tr = table.rows;
for (var i = 0; i < tr.length; i++) {
tr[i].insertBefore(tr[i].lastElementChild, tr[i].firstElementChild);
}
}
I am trying to add an onclick function to this table. So when I click on the cell it will change color from red to blue.
Relevant code below:
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<ruudud.value; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<ruudud.value; j++){
var td = document.createElement('TD');
td.width='50';
td.height='50';
td.style.backgroundColor="red";
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
There is many ways to do this as the below :
1 - In for loop
<div id="myDynamicTable"></div>
<script type="text/javascript">
addTable();
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3 ; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 2; j++) {
var td = document.createElement('TD');
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
//************************************************
td.setAttribute("onclick", "yourFun(this)");
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function yourFun(tdObj) {
tdObj.style.backgroundColor = "green";
}
2 - By Function :
<div id="myDynamicTable"></div>
<script type="text/javascript">
addTable();
setFunction();
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3 ; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 2; j++) {
var td = document.createElement('TD');
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function setFunction() {
var myTableDiv = document.getElementById("myDynamicTable");
var tds = myTableDiv.getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
tds[i].setAttribute("onclick", "yourFun(this)");
}
}
function yourFun(tdObj) {
tdObj.style.backgroundColor = "green";
}
3- Or You can use Event Delegation see this http://davidwalsh.name/event-delegate
You can do it by setting the onclick attribute for each td in your for loop which calls a corresponding function to handle a class change. The colors can be defined in your css for the two classes.
// for loop addition
td.setAttribute('class', 'bgRed');
// and
td.setAttribute('onclick', chgColor(this));
// or
td.onclick(function(this) {return function() {chgColor(this);};})(this);
// Function for changing td background class/color
function chgColor(td){
td.className == "bgRed" ? td.className = "bgBlue" : td.className = "bgRed";
}
You can directly add the event listener on the table, and in the callback you can check the event source and act accordingly. The event source would be a node so if you want to hold any specific data, you can keep attributes and read them on event.
I have made an html table with java script but not understanding how to add the caption and the thead.
var arr =[
["Period Ends", "Payroll Due", "Payday"],
["06/13/15", "06/19/15", "06/26/15"],
];
var body, tab, th, tr, td, tn, row, col;
body = document.getElementsByTagName('body')[0];
tab = document.createElement('table');
for (row=0; row < arr.length; row++){
tr = document.createElement('tr');
for (col=0; col < arr[row].length; col++){
td = document.createElement('td');
tn = document.createTextNode(arr[row][col]);
td.appendChild(tn);
tr.appendChild(td);
}
tab.appendChild(tr);
}
body.appendChild(tab);
This is the approach that I would use
var arr =[
["Period Ends", "Payroll Due", "Payday"],
["06/13/15", "06/19/15", "06/26/15"],
];
var body = document.getElementsByTagName('body')[0];
var tab = document.createElement('table');
var cap = tab.createCaption();
var tr, td, col;
// set caption
cap.innerHTML = 'My Table Caption';
// start from first row (skip row headings)
for (var row=1; row < arr.length; row++){
tr = tab.insertRow(row-1);
for (col=0; col < arr[row].length; col++){
td = tr.insertCell(col);
td.innerHTML = arr[row][col];
}
}
// add row headings
var header = tab.createTHead()
var headerRow = header.insertRow(0);
for (col=0; col < arr[0].length; col++){
td = headerRow.insertCell(col);
td.innerHTML = arr[0][col];
}
body.appendChild(tab);
This makes use of the HTML-spec methods for creating table elements
createCaption
insertRow
createTHead
insertCell
innerHTML
The only quirk I found was that I had to add the tHead after the body rows
Here's a jsfiddle