Display the existing json data to matrix like table - javascript

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>

Related

How do I set an on click event for every cell that calls a function which takes id of cell as a parameter in JavaScript

Here I created a table and assigned each cell an id. What I want to do is something like this cell1.onclik = MyFunction(this.id);
function createTable() {
var table = document.getElementById("tabela2");
for (let j = 0; j < k; j++) {
var row = table.insertRow(0);
for (let i = 0; i < l; i++) {
var cell1 = row.insertCell(0);
cell1.id = "celica" + i + "_" + j;
/*doesnt work: cell1.onclik = MyFunction(this.id); */
}
}
}
Don't use onXXX events. It won't work it there is a content-security-policy on the page.
You just need to listen to the table
function createTable() {
var table = document.getElementById("tabela2");
// document.body.appendChild(table);
for (let j = 0; j < 4; j++) {
var row = table.insertRow(0);
for (let i = 0; i < 4; i++) {
var cell1 = row.insertCell(0);
cell1.textContent = "1";
cell1.id = "celica" + i + "_" + j;
}
}
table.addEventListener("click", function(e) {
console.log(e.target.id);
console.log(e.target.tagName);
});
}
createTable();
<html><body><table id='tabela2'></table></body></html>

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>

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

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

onclick is not working

var rowcount = 0;
function addrow() {
rowcount++;
console.log("nis" + rowcount);
if (rowcount >= 2) {
return false;
rowcount = 0;
}
document.getElementById("myTableData").style.display = "block";
var el = document.createElement('input');
el.type = 'text';
el.name = 'kname' + rowcount;
var hid = document.createElement('input');
hid.type = 'hidden';
hid.name = 'hid';
hid.value = rowcount;
var del = document.createElement('input');
del.type = 'button';
del.name = 'delll';
del.value = '';
del.style.width = '30px';
del.style.height = '26px';
del.style.border = 'none';
del.style.outline = 'none';
del.style.background = 'url(./images/del-hover.png) no-repeat';
del.onclick = function () {
tr.parentElement.removeChild(tr);
rowcount--;
if (rowcount == 0 || rowcount >= 2) {
document.getElementById("myTableData").style.display = "none";
rowcount = 0;
}
};
var el_r = document.createElement('input');
el_r.type = 'radio';
el_r.name = 'kgender' + rowcount;
el_r.value = 'female';
el_r.defaultChecked = true;
var el_r2 = document.createElement('input');
el_r2.type = 'radio';
el_r2.name = 'kgender' + rowcount;
el_r2.value = 'male';
var obj1 = document.createTextNode("Female");
var obj2 = document.createTextNode("Male");
var objLabel = document.createElement("label");
objLabel.htmlFor = el_r.id;
objLabel.appendChild(el_r);
objLabel.appendChild(obj1);
var objLabel2 = document.createElement("label");
objLabel2.htmlFor = el_r2.id;
objLabel2.appendChild(el_r2);
objLabel2.appendChild(obj2);
var el_s = document.createElement('select');
el_s.name = "day1" + rowcount;
el_s.onchange = function () {
value_d = el_s.options[el_s.selectedIndex].value;
};
for (var i = 1; i < 32; i++) {
var j = i;
j = document.createElement('option');
j.text = i;
j.value = i;
el_s.appendChild(j);
}
var month = new Array("January", "Februray", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var el_sm = document.createElement('select');
el_sm.name = "month1" + rowcount;
el_sm.onchange = function () {
var valuem = el_sm.options[el_sm.selectedIndex].value;
};
for (var i = 0; i < month.length; i++) {
var j = i;
j = document.createElement('option');
j.text = month[i];
j.value = i + 1;
el_sm.appendChild(j);
}
var el_sy = document.createElement('select');
el_sy.name = "year1" + rowcount;
el_sy.onchange = function () {
var valuey = el_sy.options[el_sy.selectedIndex].value;
};
for (var i = 2013; i > 1950; i--) {
var j = i;
j = document.createElement('option');
j.text = i;
j.value = i;
el_sy.appendChild(j);
}
var table = document.getElementById("myTableData");
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD');
td.width = '175';
td.appendChild(el);
tr.appendChild(td);
var td = document.createElement('TD');
td.width = '245';
td.appendChild(objLabel);
td.appendChild(objLabel2);
tr.appendChild(td);
var td = document.createElement('TD');
td.width = '245';
td.appendChild(el_s);
td.appendChild(el_sm);
td.appendChild(el_sy);
tr.appendChild(td);
var td = document.createElement('TD');
td.width = '20';
td.appendChild(del);
tr.appendChild(td);
var td = document.createElement('TD');
td.width = '10';
td.appendChild(hid);
tr.appendChild(td);
myTableData.appendChild(table);
}
my html
<td colspan="4">
<div id="myTableData" style="display:none;">
<table>
<tr>
<td width="175">NAME</td>
<td width="245"> Gender</td>
<td width="245">Date of Birth</td>
</tr>
</table>
</div>
</td>
<td colspan="2">
<div class="addkidbg" onClick="addrow()" />ADDKID</div>
</td>
when i click on the addrow button its show me the three rows but i need the user to click only one time , if the user delete row and column name should be gone but if i click on addrow button twice and then click on the delete button .......den its showing me the column name . I want the whole part should b gone if the user delete the row and it can't clicked more than once
function addrow() {
rowcount++;
console.log("nis" + rowcount);
if (rowcount >= 2) {
rowcount = 0;
return false;
}
}
<div class="addkidbg" onClick="return addrow();" />ADDKID</div>
Try this code. Your function returns a value so write the return first on onclick event

Categories

Resources