I am making a table in which I am inserting data using a json file.
Now my json file has some links. I want those links not to be directly inserted in the table but the links should be inserted in the button in one of the columns of table so that when I click that button I am redirected to the link.
Here is my html code:
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table
From JSON" />
<p id="showData"></p>
<script type="text/javascript" src="csvjson.json"></script>
<script>
function CreateTableFromJSON() {
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < links.length; i++) {
for (var key in links[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < links.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = links[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A
CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
Here is the json file:
var links=[
{
"File": "1. Google",
"Direct Link": "https://www.google.com",
}]
You can check the property name to wrap them in button like anchor tag:
var links=[{
"File": "1. Google",
"Direct Link": "https://www.google.com",
}];
function CreateTableFromJSON() {
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < links.length; i++) {
for (var key in links[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < links.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
if(col[j] == 'Direct Link')
tabCell.innerHTML = `<a class=button href=${links[i][col[j]]}>${links[i][col[j]]}</a>`;
else
tabCell.innerHTML = links[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
.button {
font: bold 11px Arial;
text-decoration: none;
background-color: #EEEEEE;
color: #333333;
padding: 2px 6px 2px 6px;
border-top: 1px solid #CCCCCC;
border-right: 1px solid #333333;
border-bottom: 1px solid #333333;
border-left: 1px solid #CCCCCC;
cursor: pointer;
}
<input type="button" onclick="CreateTableFromJSON()" value="Create Table
From JSON" />
<p id="showData"></p>
Add anchor element. Change tabCell.innerHTML = links[i][col[j]]; with tabCell.innerHTML = "" + links[0]["File"] + "";
Related
I'm making a program that generates 2 tables. First has 16 images that represent a menu or options that you can click and then by clicking it you select in. The second table is generated by inputting rows and cells. So the second table is by default blank and each cells is meant to by replaced by an image that you selected in the first table. I've managed to do everything but I don't completley understand how to do the selecting and setting the image. (I assume it has something to do with ids and then onclick()?)
stolpci = window.prompt("vpiši stevilo stolpcov:");
for (i2 = 0; i2 < 1;) {
if (stolpci < 11 || stolpci > 41) {
stolpci = window.prompt("Napačno število. Število mora biti večje od 10 in manjše od 40. Ponovno vpiši stevilo stolpcov:");
} else {
i2++;
}
}
vrstice = window.prompt("vpiši stevilo vrstic:");
for (i2 = 0; i2 < 1;) {
if (vrstice < 6 || vrstice > 11) {
vrstice = window.prompt("Napačno število. Število mora biti večje od 5 in manjše od 11. Ponovno vpiši stevilo vrstic:");
} else {
i2++;
}
}
function generateTable() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
for (let i = 0; i < vrstice; i++) {
const row = document.createElement("tr");
row.id = i;
for (let j = 0; j < stolpci; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(' ');
cell.appendChild(cellText);
row.appendChild(cell);
cell.id = j;
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
function options() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
let nImage = 1;
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode("");
if (nImage > 16) {
nImage = 1;
}
cell.style.backgroundImage = "url('images/sprite" + nImage + ".gif')";
cell.id = nImage;
nImage++;
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
window.onload = () => {
options();
generateTable();
}
table {
border: 1px solid gray;
padding: 0px;
margin: 0px;
border-spacing: 0px;
}
td {
margin: 0px;
padding: 0px;
min-width: 32px;
max-width: 32px;
max-height: 32px;
min-height: 32px;
width: 32px;
height: 32px;
border: 1px solid gray;
background-color: silver;
}
You would need to add click events to each cell. When click you could have another object which you save the 'selected' data to i.e the cell data. You would then need a button which when clicked would move your 'selected' data to the cells in the other table.
Please I am building a dynamic table and I want when j==3; two different buttons(add and reject buttons) should be added. I don't know the best way it will appear in JSON format. And when I looped, I got only one button on the table. Is there a possible way to do this better? I am new to javaScript.
**This is js **
var contributionTable = document.querySelector("#contributionTable");
if(myContribution.contributions.length>0){
var col = [];
for (var i = 0; i < myContribution.contributions.length; i++) {
for (var key in myContribution.contributions[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.querySelector("#tableHead");
var hRow = document.querySelector("#tableRow");
tHead.appendChild(hRow);
contributionTable.appendChild(tHead);
var tBody = document.createElement("tbody");
for (var i = 0; i < myContribution.contributions.length; i++) {
var bRow = document.createElement("tr");
var td = document.createElement("td");
td.innerHTML = i+1;
bRow.appendChild(td);
for (var j = 0; j < 4; j++) {
var td = document.createElement("td");
if (j==3) {
for (let i = 0; i < myContribution.contributions.length; i++) {
let modify = myContribution.contributions[i].modify;
for(let j = 0; j < modify.length; j++){
if (td.textContent==="Accept") {
td.innerHTML='<div class="badge badge-success">'+modify[j]+'</div>';
bRow.appendChild(td);
}else
td.innerHTML='<div class="badge badge-danger">'+modify[j]+'</div>';
bRow.appendChild(td);
}
}
}else{
td.innerHTML = myContribution.contributions[i][col[j]];
bRow.appendChild(td);
}
}
tBody.appendChild(bRow)
}
contributionTable.appendChild(tBody);
}
with the above, I got only the reject button but I want both the add and reject buttons to appear on the same cell in each row.
This is my JSON data
var myContribution = {"contributions":
[
{
"txnNo":"00031",
"name": "Onyinye Okeke",
"Delete":"Delete",
"modify":["Accept","Reject"],
"date":"2020-01-19",
"amount":"100000",
"desc": "Weekly"
},
{
"txnNo":"00031",
"name": "Thompson Philip",
"Delete":"Delete",
"modify":["Accept","Reject"],
"date":"2019-11-09",
"amount":"70000",
"desc": "Daily"
}]}
Perhaps something like this?
var cellContent = '';
for(let j = 0; j < modify.length; j++) {
if (td.textContent==="Accept")
cellContent +='<div class="badge badge-success">'+modify[j]+'</div>';
else
cellContent +='<div class="badge badge-danger">'+modify[j]+'</div>';
}
td.innerHTML = cellContent;
bRow.appendChild(td);
If you want to add styles to the buttons, it is better to update button style using CSS
td > div.badge {
margin: 0 5px; /* no space on top, 5px right space, no bottom space, 5px left space
}
I'm working on a real-life timetable where you can watch where the students current be. They have six meetings a day. if a student exit the scool i want to delete him from the list. if i doubleclick the name i want to change the class from name to selected and change the backgoundcolor so if i would press the "Schüler löschen"-button all selected get deleted.
Here is the code:
function createTable(){
var table = document.getElementById('table');
for(var j = 0;j<names.length;j++) {
var row = document.createElement("tr");
row.classList.add('row');
for(i=0;i<8;i++){
if(i==0){
var cell = document.createElement("input");
cell.classList.add('name');
cell.value= names[j];
cell.addEventListener("dblclick", function(){
alert(cell.classList);
cell.classList.add('selected');
alert(cell.classList);
});
}else if(i==4){
var cell = document.createElement("td");
cell.classList.add('spacer');
}else{
var cell = document.createElement("td");
cell.classList.add('cell');
cell.textContent = '';
}
row.appendChild(cell);
}
table.children[0].appendChild(row);
}
}
createTable();
the css:
input.name {
width: 20em;
background-color: #00ff00;
}
input.selected{
background-color: #ff7f7f;
}
The problem is if i double click the field the color dosent switch to red it stays green but the alert()-function shows that the class has switched
i've also tried
cell.name {
width: 20em;
background-color: #00ff00;
}
cell.selected{
background-color: #ff7f7f;
}
You need to remove cell class, and use this in that scope.
Try this:
function createTable() {
var table = document.getElementById('table');
var names = ["TEST 1", " TEST 2"];
for (var j = 0; j < names.length; j++) {
var row = document.createElement("tr");
row.classList.add('row');
for (i = 0; i < 8; i++) {
if (i == 0) {
var cell = document.createElement("input");
cell.classList.add('name');
cell.value = names[j];
cell.addEventListener("dblclick", function () {
alert(cell.classList);
this.classList.remove('cell');
this.classList.add('selected');
alert(cell.classList);
});
} else if (i == 4) {
var cell = document.createElement("td");
cell.classList.add('spacer');
} else {
var cell = document.createElement("td");
cell.classList.remove('selected');
cell.classList.add('cell');
cell.textContent = '';
}
row.appendChild(cell);
}
table.children[0].appendChild(row);
}
}
createTable();
input.name {
width: 20em;
background-color: #00ff00;
}
input.selected{
background-color: #ff7f7f;
}
<table id="table"><tbody></tbody></table>
I didn't get why cell is input element and why do you need to added in tr
I`m working with PLC controllers. I have created a webserver on a PLC and I want to show data block in html. I already know that I must write:
:="webdata".counter[0]:
But I have 2 problems.
1) I want to load this data in table and here is a problem. When i try:
for(var r = 0; r < 3; r++) {
document.write(":=\"webdata\".test[" + r + "]:")
};
There is nothing in page (in PLC i have an array of 55). So I`ve created an array and table
var edr = [
{
"Pallet": ":="webdata".test[0]:",
"code": "8501H984P",
"Cycles": ":="pallet_data".cycles[0]:"
},
{
"Pallet": ":="webdata".test[1]:",
"code": "8501H984P",
"Cycles": ":="pallet_data".cycles[1]:"
}
]
var col = [];
for (var i = 0; i < edr.length; i++) {
for (var key in edr[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < edr.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = edr[i][col[j] ];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
And this works but I have to type whole array. Is there a solution of this?
2) Also to update data I use jQuery
$(document).ready(function(){
$.ajaxSetup({ cache: false });
setInterval(function() {
$.get("IO.html", function(result){
$('#counter').text(result.trim());
});
},3000);
});
but I have to create a html file with :="webdata".test[0]: inside. I cannot find a solution to extract only a part of html document.
I will be grateful for your help :)
Right now I cannot figure out how to add headers for all the columns in this code where a html-table are created dynamically
function createTableAndInsert(sqlArray) {
//create table dynamically - only one row by the moment
var table = document.createElement('table');
for (var i = 1; i < 2; i++) {
var tr = document.createElement('tr'); // row
for (var j = 0; j < 8; j++) {
var td = document.createElement('td'); //column
var text = document.createTextNode(sqlArray[j]); //cell
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);
}
You can pass the header list separately to your function and add following code
function createTableAndInsert(sqlArray,headerList) {
var table = document.createElement('table');
var tr = document.createElement('tr'); // Header row
for (var j = 0; j < 8; j++) {
var th = document.createElement('th'); //column
var text = document.createTextNode(headerList[j]); //cell
th.appendChild(text);
tr.appendChild(th);
}
table.appendChild(tr);
for (var i = 1; i < 2; i++) {
var tr = document.createElement('tr'); // row
for (var j = 0; j < 8; j++) {
var td = document.createElement('td'); //column
var text = document.createTextNode(sqlArray[j]); //cell
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);
}
Your structure is:
<tr>
<td>
<div></div>
<div></div>
</td>
</tr>
thead should be appended before each row.
<thead></thead>
<tr>
<td>
<div></div>
<div></div>
</td>
</tr>
Solution:
var thead = document.createElement('thead');
thead.innerHTML = 'Header';
Before table.appendChild(tr);, add this line table.appendChild(thead);
THEAD needs one or more TR elements:
var table = document.createElement('table'); // 'table' may be a reserved word
var tblHead = document.createElement('thead');
var rowHead = document.createElement('tr');
table.appendChild(tblHead);
tblHead.appendChild(rowHead)
for(j=0; j<8; j++) {
var celHead = document.createElement('th');
//the array txtHeaders[] should be passed to your function if you have the values in advance
// otherwise, you can access the header cells later by:
// table.getElementsbyTagName('th')[].innerHTML
celHead.innerHTML = txtHeaders[j]
rowHead.appendChild(celHead)
}
// now do your row & table loops