Adding two different buttons on each cells dynamically - javascript

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
}

Related

How can I set an image as an td background?

I'm trying to set each td as a different image that I have saved as imgn.gif. (n being image number, I have 13 images, img1.gif., img2.gif... img13.gif) I have a code that generates the table now I just can't figure out how to set a background image, preferably so that the n imgn.gif changes to the next index so the next td will have the next image.
this is the code that I have for now. I assume I have to set something differently here: const cellText = document.createTextNode(2);, so it sets background-image instead?
function options ()
{
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
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(2);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
just add 5 lines in you actual code:
options();
function options() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
const nbImage = 13;
let curImage = 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");
if (curImage > nbImage) {
curImage = 1;
}
cell.style.backgroundImage = 'url(img' + curImage + '.gif)';
const cellText = document.createTextNode(2);
cell.appendChild(cellText);
row.appendChild(cell);
curImage += 1;
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
I've added:
nbImage (13 from your post)
curImage to iterate through your 13 images
After your cell creation, checking the image number:
if (curImage > nbImage) {
curImage = 1;
}
So your fourteenth TD will have the image 1
Your is already created as a DOM element so you can refer it and add a background image:
cell.style.backgroundImage = 'url(img' + curImage + '.gif)';
That will add for each TD a backgound image "img1.gif", "img2.gif"... till "img13.gif", after "img1.gif" ... and so on...
You can create a variable (nImage for exemple) starting from 1 to 13 and reset it when up to 13 so it came back to 1. Then use this variable to modify style.backgroundImage of your td :
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(2);
if (nImage > 13){nImage =1 ;}
cell.style.backgroundImage = "url('yourPathTo/img"+nImage + ".gif')" ;
nImage++ ;
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}

How to read an array/data from other html file in jQuery and create dynamic table (PLC webserver)

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

Multiplication table using appendchild and html table

Could anyone help me make a multiplication table, 0-10 in an 11x11 table?
I need to use createElement/appendchild. When I use document write, it almost look complete, just miss the placement of the blue columns/rows.
It should look something like this (Only need the numbers, no fancy outline):
This is what I've got so far:
for(var i = 0; i < 1; i++){
var tabell1 = document.createElement("table");
tabell.appendChild(tabell1);
//document.write("<table>");
for(var j = 0; j<11; j++){
var rad = document.createElement("tr");
tabell.appendChild("tr");
//document.write("<tr>");
for(var k = 1; k<=11; k++){
var kolonne = document.createElement("td");
tabell.appendChild(kolonne);
kolonne.innerHTML = k*(j+1);
//document.write("<td>"+ k*(j+1) +"</td>");
}
//document.write("</tr>");
}
//document.write("</table>")
}
<div id="tabell"></div>
You can generate the table using two loops.
You iterate twice from 0 to 10 included.
Use use the value 0 to represent your top row and first column, which hold the numbers to be multiplied. Since the iterator starts at 0, the value will be 0 and you can use that to detect when to add the header class and set the value to your non-zero iterator, either i or j:
const table = document.createElement('table');
for (let i = 0; i <= 10; i++){
const row = document.createElement('tr');
for (let j = 0; j <= 10; j++){
const col = document.createElement('td');
let val = i * j;
if (val === 0) {
val = i || j;
val = val ? val : '';
col.classList.add('header');
}
col.innerHTML = val;
row.appendChild(col);
}
table.appendChild(row);
}
document.body.appendChild(table);
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 3px;
text-align: center;
}
.header {
background: #ccf;
}
The blue border can be obtained by css. See my code. I only changed four lines of loop
function createTables(maxNum,limit){
const table = document.createElement('table');
for(let i = 0;i<maxNum + 1;i++){
const row = document.createElement('tr');
for(let j = 0;j<limit + 1;j++){
const td = document.createElement('td');
//Below four lines are new
if(i === 0 && j === 0) td.innerHTML = '';
else if(i === 0) td.innerHTML = j;
else if(j === 0) td.innerHTML = i;
else td.innerHTML = i*j;
row.appendChild(td);
}
table.appendChild(row)
}
document.body.appendChild(table)
}
createTables(10,15);
table{
border-collapse:collapse;
}
td{
padding:20px;
font-size:25px;
background-color:gray;
border:2px solid black;
text-align:center;
vertical-align:center;
color:white;
}
tr > td:nth-child(1),tr:nth-child(1) > td{
background:blue;
}
I think best to use inserRow and insertCell
Cheers!
for (var i = 0; i < 1; i++) {
var tabell1 = document.createElement("table");
tabell.appendChild(tabell1);
for (var j = 0; j < 11; j++) {
var row = tabell1.insertRow(j);
for (var k = 0; k <= 10; k++) {
var cell = row.insertCell(k);
if (j == 0 && k == 0) {
//if first row and first column do nothing
} else if (j == 0) {
//else if first row
cell.innerHTML = k * (j + 1);
} else if (k == 0) {
//else if first column
cell.innerHTML = j;
} else {
//else multiply
cell.innerHTML = k * (j);
}
}
}
}
<div id="tabell"></div>

How "tblGene()" call on JavaScript page.I am want to call on HTML page using onclick.. Without click this Json table show on my web page

How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
<div id="showData"></div>
var people, asc1 = 1;
function tblGene() {
var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
tbody.id = "people";
var tbl = document.createElement("table");
tbl.id = "tblSample";
var col = [];
for (var i = 0; i < data.length; i++) {
for (var colHdr in data[i]) {
if (col.indexOf(colHdr) === -1) {
col.push(colHdr);
}
}
}
var tr = tbl.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
th.dataset.key = i;
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i = 0; i < data.length; i++) {
tr = tbl.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
tbody.appendChild(tr);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
var divCntr = document.getElementById("showData");
divCntr.innerHTML = "";
divCntr.appendChild(tbl);
thead.addEventListener("click", function(event) {
var key = event.target.dataset.key;
people = document.getElementById("people");
sort_tbl(people, key, asc1);
});
function sort_tbl(tblSample, key, asc) {
var rows = tblSample.rows,
rlen = rows.length,
arr = new Array();
for (var i = 0; i < rlen; i++) {
var cells = rows[i].cells;
var clen = cells.length;
arr[i] = new Array();
for (var j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(x, y) {
if (isNaN(x[key]) && isNaN(y[key])) {
var a = String(x[key]).toUpperCase();
var b = String(y[key]).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
} else {
return x[key] - y[key];
}
});
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
}
Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.

Combine HTML Table Rows with Javascript

Is there an easy way to combine rows in an HTML table where the first column is the same? I basically have a table set up like:
<table>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
</table>
and I want it to generate:
<table>
<tr><td>test</td><td>37035</td><td>37035</td><tr>
<tr><td>test2</td><td>24690</td><td>24690</td><tr>
</table>
using jQuery:
var map = {};
$('table tr').each(function(){
var $tr = $(this),
cells = $tr.find('td'),
mapTxt = cells.eq(0).text();
if(!map[mapTxt]){
map[mapTxt] = cells;
} else {
for(var i=1, l=cells.length; i<l; i++){
var cell = map[mapTxt].eq(i);
cell.text(parseInt(cell.text()) + parseInt(cells[i].text()));
}
$tr.remove();
}
});
this is a "dumb" script -- no error handling for cases like different number of cells, fields being non-numeric, etc. Add those if necessary.
Also, depending on how it's generated, it's better to do this server-side.
Here's a plain JavaScript version.
window.onload = function() {
var table = document.getElementById('mytable');
var tr = table.getElementsByTagName('tr');
var combined = Array();
for (i = 0; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var key = td[0].innerText;
if (!combined[key]) {//if not initialised
combined[key] = Array();
for (j = 0; j < td.length - 1; j++) combined[key][j] = 0;
}
for (j = 0; j < td.length - 1; j++)
combined[key][j] += parseInt(td[j + 1].innerText);
}
while (table.hasChildNodes()) table.removeChild(table.lastChild);
var tbody = document.createElement('tbody');//needed for IE
table.appendChild(tbody);
for (var i in combined) {
tr = document.createElement('tr');
tbody.appendChild(tr);
td = document.createElement('td');
td.innerText = i;
tr.appendChild(td);
for (j = 0; j < combined[i].length; j++) {
td = document.createElement('td');
td.innerText = combined[i][j];
tr.appendChild(td);
}
}
}
This will work on tables with any number of rows and any number of cells. I suppose you want to make the sum for every column, that's what this script does.
And as cwolves mentioned, it is more logical to do this serverside. Users that have JS disabled will see the not so clean uncombined table.

Categories