Table Javascript - javascript

I'm a beginner in JavaScript.
Considering the following code I would like to have one different name in each cell but can not understand how to do it :
function tableCreate() {
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '3em';
tbl.style.border = '1px solid black';
tbl.style.borderCollapse = 'collapse';
for (var i = 0; i < 5; i++) {
var tr = tbl.insertRow();
for (var j = 0; j < 1; j++) {
if (i == 2 && j == 1) {
break;
} else {
var td = tr.insertCell();
td.appendChild(document.createTextNode('Luke'));
td.style.border = '1px solid black';
if (i == 1 && j == 1) {
td.setAttribute('rowSpan', '2');
}
}
}
}
body.appendChild(tbl);
}
tableCreate();
Do anyone have an idea how should I proceed?

You are always adding Luke!
td.appendChild(document.createTextNode('Luke'));
Just create an array of names and use it inside the loop. As simple as that.
See a working snippet here:
function tableCreate() {
var names = ['Luke', 'Skywalker', 'Anakin', 'Darth', 'Vader'];
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '3em';
tbl.style.border = '1px solid black';
tbl.style.borderCollapse = 'collapse';
for (var i = 0; i < 5; i++) {
var tr = tbl.insertRow();
for (var j = 0; j < 1; j++) {
if (i == 2 && j == 1) {
break;
} else {
var td = tr.insertCell();
td.appendChild(document.createTextNode(names[i]));
td.style.border = '1px solid black';
if (i == 1 && j == 1) {
td.setAttribute('rowSpan', '2');
}
}
}
}
body.appendChild(tbl);
}
tableCreate();

You can all keep different names in an array and then use it as you create your cells.
Something like below
function tableCreate() {
var namesArray = [ 'Luke', 'Hans', 'Leia', 'Chewbacca', 'Yoda'];
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '3em';
tbl.style.border = '1px solid black';
tbl.style.borderCollapse = 'collapse';
for (var i = 0; i < 5; i++) {
var tr = tbl.insertRow();
for (var j = 0; j < 1; j++) {
if (i == 2 && j == 1) {
break;
} else {
var td = tr.insertCell();
td.appendChild(document.createTextNode(namesArray[i]));
td.style.border = '1px solid black';
if (i == 1 && j == 1) {
td.setAttribute('rowSpan', '2');
}
}
}
}
body.appendChild(tbl);
}
tableCreate();

If i correctly understood your question , you are trying to insert different text each time. Here is how.
function tableCreate(){
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '3em';
tbl.style.border = '1px solid black';
tbl.style.borderCollapse = 'collapse';
for(var i = 0; i < arguments.length; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 1; j++){
if(i == 2 && j == 1){
break;
} else {
var td = tr.insertCell();
td.appendChild(document.createTextNode(arguments[i]));
td.style.border = '1px solid black';
if(i == 1 && j == 1){
td.setAttribute('rowSpan', '2');
}
}
}
}
body.appendChild(tbl);
}
tableCreate('First','Second','Third','Fourth','Fifth');

Related

Send a grid as json

I'm relatively new to the world of JavaScript. I create a grid in which I can select any cells.
Now I would like to send all cells as binary with a Json document to the backend. For this purpose, an unselected cell should have a 0 and a selected one should have a 1. I orientate myself on Conway's Game of Life. I've been at it for 2 days now and don't know how best to implement it. Does anyone have an idea?
Here is my code to create the grid
var rows = 10;
var cols = 10;
var grid = new Array(rows);
var nextGrid = new Array(rows);
var startButton = document.getElementById('start');
startButton.addEventListener('click', event => {
initialize()
})
function initializeGrids() {
for (var i = 0; i < rows; i++) {
grid[i] = new Array(cols);
nextGrid[i] = new Array(cols);
}
}
function copyAndResetGrid() {
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
grid[i][j] = nextGrid[i][j];
}
}
}
// Initialize
function initialize() {
createTable();
initializeGrids();
}
// Lay out the board
function createTable() {
var gridContainer = document.getElementById('gridContainer');
if (!gridContainer) {
// Throw error
console.error("Problem: No div for the drid table!");
}
var table = document.createElement("table");
for (var i = 0; i < rows; i++) {
var tr = document.createElement("tr");
for (var j = 0; j < cols; j++) {
var cell = document.createElement("td");
cell.setAttribute("id", i + "_" + j);
cell.setAttribute("class", "dead");
cell.onclick = cellClickHandler;
tr.appendChild(cell);
}
table.appendChild(tr);
}
gridContainer.appendChild(table);
}
function cellClickHandler() {
var rowcol = this.id.split("_");
var row = rowcol[0];
var col = rowcol[1];
var classes = this.getAttribute("class");
if(classes.indexOf("live") > -1) {
this.setAttribute("class", "dead");
grid[row][col] = 0;
} else {
this.setAttribute("class", "live");
grid[row][col] = 1;
}
}

Set type text inside cell javascript

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>

Display the existing json data to matrix like table

I would like to display the json data to the table. Tried key value pattern. But no luck. Could anyone suggest me? Thanks.
my full JSON data contains around 20 objects. This is a dynamic created table according to other table's value -- example has 3. So when it's three rows, only three rows should be filled from the JSON data if exists. For example if 5 rows, 3 rows should be filled from the json and two rows should display '-'.
function setTrait_matrix() {
var json_data = {
Title1_Title1: "11yty",
Title1_Title2: "12sdf",
Title1_Title3: "1376",
Title2_Title1: "21yu",
Title2_Title2: "22",
Title2_Title3: "235",
Title3_Title1: "31",
Title3_Title2: "32",
Title3_Title3: "33"
};
var matrixVal = 3;
if (matrixVal != 0 || matrixVal != null) {
var root = document.getElementById("traits_matrix_Div");
var table = document.createElement('table');
table.className = "difftable";
var tblB = document.createElement('tbody');
table.appendChild(tblB);
var firstList = {};
for (var x = 1; x <= matrixVal; x++) {
firstList['Title' + x] = 'Title' + x;
}
myData = Object.values(firstList);
var tr = document.createElement('tr');
tr.appendChild(document.createElement('th'));
for (var j = 0; j < matrixVal; j++) {
var th = document.createElement('th');
var text = document.createTextNode(myData[j]);
th.appendChild(text);
tr.appendChild(th);
}
tblB.appendChild(tr);
for (var i = 0; i < matrixVal; i++) {
var tr = document.createElement('tr');
tblB.appendChild(tr);
var td = document.createElement('td');
var text = document.createTextNode(myData[i]);
td.appendChild(text);
tr.appendChild(td);
var thisMatrix = JSON.stringify(json_data);
var curcolumn = i + 1;
for (var j = 0; j < matrixVal; j++) {
var input = document.createElement("input");
input.type = "text";
if (typeof thisMatrix !== 'undefined') {
var curValue = "jsonVal";
} else {
var curValue = "-"
}
var col = j + 1;
if (i >= 0 && j >= 0) {
input.name = "Title" + curcolumn + "_Title" + col;
input.value = curValue;
input.id = "Title" + curcolumn + "_Title" + col;
}
const td = document.createElement('td');
td.appendChild(input);
tr.appendChild(td);
}
}
root.appendChild(table);
}
}
<body onload="setTrait_matrix()">
<div id="traits_matrix_Div" style="visibility:visible" style="border: 1px; height:200px; align: center;"></div>
</body>
Hope I am not confusing. Please suggest me!
function setTrait_matrix() {
var json_data = {
Title1_Title1: "11yty",
Title1_Title2: "12sdf",
Title1_Title3: "1376",
Title2_Title1: "21yu",
Title2_Title2: "22",
Title2_Title3: "235",
Title3_Title1: "31",
Title3_Title2: "32",
Title3_Title3: "33"
};
var matrixVal = 3;
if (matrixVal != 0 || matrixVal != null) {
var root = document.getElementById("traits_matrix_Div");
var table = document.createElement('table');
table.className = "difftable";
var tblB = document.createElement('tbody');
table.appendChild(tblB);
var firstList = {};
for (var x = 1; x <= matrixVal; x++) {
firstList['Title' + x] = 'Title' + x;
}
myData = Object.values(firstList);
var tr = document.createElement('tr');
tr.appendChild(document.createElement('th'));
for (var j = 0; j < matrixVal; j++) {
var th = document.createElement('th');
var text = document.createTextNode(myData[j]);
th.appendChild(text);
tr.appendChild(th);
}
tblB.appendChild(tr);
for (var i = 0; i < matrixVal; i++) {
var tr = document.createElement('tr');
tblB.appendChild(tr);
var td = document.createElement('td');
var text = document.createTextNode(myData[i]);
td.appendChild(text);
tr.appendChild(td);
var thisMatrix = JSON.stringify(json_data);
var curcolumn = i + 1;
for (var j = 0; j < matrixVal; j++) {
var input = document.createElement("input");
input.type = "text";
if (typeof json_data["Title"+(i+1)+"_Title"+(j+1)] !== 'undefined') {
var curValue = json_data["Title"+(i+1)+"_Title"+(j+1)];
} else {
var curValue = "-"
}
var col = j + 1;
if (i >= 0 && j >= 0) {
input.name = "Title" + curcolumn + "_Title" + col;
input.value = curValue;
input.id = "Title" + curcolumn + "_Title" + col;
}
const td = document.createElement('td');
td.appendChild(input);
tr.appendChild(td);
}
}
root.appendChild(table);
}
}
<body onload="setTrait_matrix()">
<div id="traits_matrix_Div" style="visibility:visible" style="border: 1px; height:200px; align: center;"></div>
</body>
I hope this will help you.
I just did a quick fix in your code. You weren't actually calling the JSON object data anywhere, so... I just called it like this:
let box_value = json_data["Title" + curcolumn + "_Title" + col];
input.value = box_value?box_value:"-";
function setTrait_matrix() {
var json_data = {
Title1_Title1: "11yty",
Title1_Title2: "12sdf",
Title1_Title3: "1376",
Title2_Title1: "21yu",
Title2_Title2: "22",
Title2_Title3: "235",
Title3_Title1: "31",
Title3_Title2: "32",
Title3_Title3: "33",
Title1_Title4: "1414141"
};
var matrixVal = 5;
if (matrixVal != 0 || matrixVal != null) {
var root = document.getElementById("traits_matrix_Div");
var table = document.createElement('table');
table.className = "difftable";
var tblB = document.createElement('tbody');
table.appendChild(tblB);
var firstList = {};
for (var x = 1; x <= matrixVal; x++) {
firstList['Title' + x] = 'Title' + x;
}
myData = Object.values(firstList);
var tr = document.createElement('tr');
tr.appendChild(document.createElement('th'));
for (var j = 0; j < matrixVal; j++) {
var th = document.createElement('th');
var text = document.createTextNode(myData[j]);
th.appendChild(text);
tr.appendChild(th);
}
tblB.appendChild(tr);
for (var i = 0; i < matrixVal; i++) {
var tr = document.createElement('tr');
tblB.appendChild(tr);
var td = document.createElement('td');
var text = document.createTextNode(myData[i]);
td.appendChild(text);
tr.appendChild(td);
var thisMatrix = JSON.stringify(json_data);
var curcolumn = i + 1;
for (var j = 0; j < matrixVal; j++) {
var input = document.createElement("input");
input.type = "text";
if (typeof thisMatrix !== 'undefined') {
var curValue = "jsonVal";
} else {
var curValue = "-"
}
var col = j + 1;
if (i >= 0 && j >= 0) {
input.name = "Title" + curcolumn + "_Title" + col;
let box_value = json_data["Title" + curcolumn + "_Title" + col];
input.value = box_value?box_value:"-";
input.id = "Title" + curcolumn + "_Title" + col;
}
const td = document.createElement('td');
td.appendChild(input);
tr.appendChild(td);
}
}
root.appendChild(table);
}
}
<body onload="setTrait_matrix()">
<div id="traits_matrix_Div" style="visibility:visible" style="border: 1px; height:200px; align: center;"></div>
</body>

how to add data in a dynamic table

hi i have a table which is created dynamically .this is the code for table creation
function table() {
var body = document.body,
tbl = document.createElement('table'),
tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.style.width = '100%';
id = 0;
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode(""));
}
}
$(".lefttablediv").append(tbl);
};
table();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
now it is empty table i want add different data in each tr how can i add data?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Html>
<body id ="body">
</body>
</html>
<script>
function table() {
var body = document.body;
var tbl = document.createElement('table');
var tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.style.width = '100%';
alert(tbl);
console.log(tbl);
id=0
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode("Please add some text here"));
}
}
$("#body").append(tbl);
};
table();
</script>
td.appendChild(document.createTextNode("")); you are appending blank data which showing blank page add some text it will reflect on page
***** td.appendChild(document.createTextNode("Please add sone text here"))****

Javascript random cell background color change

I am trying to create a table. ruudud.value is a value from <select>. But while this function is creating a table, I want it to place some random yellow cells in it.
This is a small school project and this code is part of a code which should createbattleship game.
Also if possible. when it does create a random yellow cell, then could it also paint the next cell yellow? (to create a 2 cell ship).
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var x = Math.floor((Math.random() * ruudud.value) + 0);
var y = Math.floor((Math.random() * ruudud.value) + 0);
for (var i = 0; i < ruudud.value; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
console.log(x + "," + y);
for (var j = 0; j < ruudud.value; j++) {
var td = document.createElement('TD');
var td = document.getElementsByTagName("td");
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
td.setAttribute("onClick", "colorChange(this)")
td.innerHTML = (i + "," + j);
if (td[i].innerHTML == (x + "," + y)) {
td[i].setAttribute("style", "background:yellow;");
}
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function colorChange(tdObj) {
tdObj.style.backgroundColor = "green";}
example2:
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var x = Math.floor((Math.random() * ruudud.value) + 0);
var y = Math.floor((Math.random() * ruudud.value) + 0);
for (var i=0; i<ruudud.value; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
console.log(x + ","+y);
for (var j=0; j<ruudud.value; j++){
var td = document.createElement('TD');
var td2 = document.getElementsByTagName("td");
var i = 0, tds = td.length;
td.width='50';
td.height='50';
td.style.backgroundColor="white";
td.setAttribute("onClick", "colorChange(this)")
td.innerHTML = (i +","+ j);
if(td2[i].innerHTML == (x + "," + y)) {
td2[i].setAttribute("style", "background:yellow;");
}
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function colorChange(tdObj) {
tdObj.style.backgroundColor = "green";}
In both the cases, you are selecting the td element before it is appended to the DOM. You don't need to select it again, you can simply apply style to the td element when you create it. Here's a slight modification to your code. I have also added a condition to add two-cell ships like you asked.
function addTable(double) {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var x = Math.floor((Math.random() * ruudud.value) + 0);
var y = Math.floor((Math.random() * ruudud.value) + 0);
for (var i = 0; i < ruudud.value; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
//console.log(x + "," + y);
for (var j = 0; j < ruudud.value; j++) {
var td = document.createElement('td');
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
td.setAttribute("onClick", "colorChange(this)");
td.innerHTML = (i + "," + j);
if (x === i && y === j) {
td.setAttribute("style", "background:yellow;");
}
// If you need to enable two-cell ships, pass true to the function
// You can allow horizontal or vertical cells by changing x and ys in the equality checks below
if(double){
if(y+1 < ruudud.value){
if(x === i && y+1 === j){
td.setAttribute("style", "background:yellow;");
}
}
else{
if(x === i && y-1 === j){
td.setAttribute("style", "background:yellow;");
}
}
}
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function colorChange(tdObj) {
tdObj.style.backgroundColor = "green";}
addTable(true);

Categories

Resources