I got a javascript with a function that creates a table. Now I want the table to be updated/replaced each time I press the button again. I have tried some solutions I have found on the web but none seem to do what I want.
javascript
//Updates table
function myFunction(jsonObject) {
//Build array from the jsonObject
var customers = new Array();
var jsonArr = jsonObject['log'];
for(var i in jsonArr){
customers.push((jsonArr[i]['date']) );
customers.push((jsonArr[i]['time']) );
customers.push((jsonArr[i]['temp']) );
customers.push((jsonArr[i]['humidity']) );
}
//Remove existing tables.-----------------------THIS HAS NO EFFECT!
var myNode = document.getElementById('logDiv');
while (myNode.hasChildNodes()) {
alert("logDiv has nodes, removing them now!")
myNode.removeChild(myNode.firstChild);
}
//----------------------------------------------THIS HAS NO EFFECT!
var container = document.getElementById('logDiv');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.className = "sortable";
//Adds table headers
var headers = ["Date", "Time", "Temp", "Hum"]
var row1 = document.createElement('tr');
for (var b = 0; b < 4; b++) {
var cell = document.createElement('th');
cell.textContent = headers[b];
row1.appendChild(cell);
counter++;
}
tbody.appendChild(row1);
var counter = 0;
// loop and create rows
for (i = 0; i < customers.length/4; i++) {
var values = customers[i];
var row = document.createElement('tr');
// loop and create columns
for (var b = 0; b < 4; b++) {
var cell = document.createElement('td');
cell.textContent = customers[counter];
row.appendChild(cell);
counter++;
}
tbody.appendChild(row);
}
table.appendChild(tbody);
container.appendChild(table);
}
html/php
<?php
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
$json = json_encode($finalOutput);
?>
<html>
<head>
<script src="script.js" type="text/javascript"></script>
<script src="sorttable.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="UTF-8">
<title>Antgus</title>
</head>
<body>
<button id="btnGenerate" type="button" onclick='myFunction(<?php echo $json ?>)'>Generate log</button>
<br><br>
<div id="logDiv"></div>
</body>
</html>
Related
I have created a table using javascript and HTML. The table has 50 cells. The cells begin at 50 and end at 1. This is what it looks like now and my code:
I am creating a snakes and ladders game. So 1 needs to begin on the left bottom corner and so on like this:
Is there a way to do this easily or do I need to program each row myself the way I want it?
This is my code so far:
Html:
<html>
<head>
<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'style.css';
document.getElementsByTagName('HEAD')[0].appendChild(link);
</script>
</head>
<html lang="en">
<body>
<div>
<button id="selectbtn" type="button" >Create </button>
<button id="btnMove" type="button" >move to ?</button>
</div>
<div id="myDynamicTable">
</div>
</body>
</html>
Script:
document.getElementById("selectbtn").addEventListener("click", addTable);
function addTable() {
document.getElementById("selectbtn").hidden=true;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
//table.className = "table";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var n = 50;
var even = true;
for (var i=0; i<5; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<10; j++){
var td = document.createElement('TD');
td.width='75';
td.height = '75';
td.id = n;
if(even){
td.className = "even"
even = false
}
else{
td.className = "odd"
even = true
}
var img = document.createElement('img');
img.id = "img"+n;
td.appendChild(img);
td.appendChild(document.createTextNode(n));
tr.appendChild(td);
n--;
}
}
myTableDiv.appendChild(table);
}
Thank you in advance
function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "31";
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var thead = document.createElement('td');
thead.classList.add("ui-droppable");
thead.appendChild(data[j]);
tre.appendChild(thead);
tbody.appendChild(tre);
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>
I'm trying to order the data that I get from my server to match the columns of my table.
My table columns are days from Monday to Sunday. When my data has more than 7items it needs to separate with another td. The td shows me week 1 and when my data has more than 7 items it needs to separate again that shows week 2 etc.
Update
Im now using a snipped verdion of my code.
Hope someone can help me out with this.
Thank you
There's a few things going on in the code that are problematic.
An attempt to add the table cells to the row, and the row to the table, was made on each iteration of the for loop. That would have produced a lot of rows with single cells had it worked.
It didn't work because there was only ever a single instance of tre, the row variable. So that meant the line tbody.appendChild(tre); did nothing, since appendChild won't append an element that already has a parent element.
Because your data was an array of references to HTMLElements with parents, appending them using appendChild did nothing for the same reason.
I've amended the code below to take care of all of these situations.
Firstly, the code will append a clone of the data to the cell if it's an HTMLElement. I expect in your real code you won't need this, but for this example, why not? It then appends the cell to the row and continues to the next data element.
Secondly, when the data iterator is at 7, before it appends the "Week N" header, it appends a clone of the row, if it has cells on it.
Finally, after appending the clone of the row, the code will reset the row variable to a new instance of a tr element, with no cells.
I also made some variable name and formatting changes to your code just so I could more easily work with it.
function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "6"; // "31"; Why 31? A week has 7 days...
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
/* Major changes start here */
// if the row has cells
if (tre.querySelectorAll('td').length) {
// clone and append to tbody
tbody.appendChild(tre.cloneNode(true));
// reset table row variable
tre = document.createElement('tr');
}
// then append the Week header
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var td = document.createElement('td');
td.classList.add("ui-droppable");
// Set the value of the cell to a clone of the data, if it's an HTMLElement
// Otherwise, make it a text node.
var value = data[j] instanceof HTMLElement ?
data[j].cloneNode(true) :
document.createTextNode(data[j]);
td.appendChild(value);
tre.appendChild(td);
}
// If the number of data elements is not evenly divisible by 7,
// the remainder will be on the row variable, but not appended
// to the tbody, so do that.
if (tre.querySelectorAll('td').length) {
tbody.appendChild(tre.cloneNode(true));
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>
Newbie coder here. I am creating an app (see below) that has 2 user input fields located side by side. Parse buttons by these user input fields generate 2 separate tables. The tables are placed vertically and I need them to be placed side by side underneath the user input fields. I've seen many solutions to this problem but they all pertain to html code. I don't know how to do that in JS. Please help! An example of user input would be: 1,2,3,4
realArrayRequest = [];
realArrayResponse = [];
function generateTableRequest(){
var body = document.body;
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for(var i=0; i<msg1Req.length; i++){ //rows
var row=document.createElement("tr");
for (var j=0; j < 3; j++){
if (j === 0){ //columns
var cell = document.createElement("td");
var cellText = document.createTextNode(msg1Req[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 1){
var cell = document.createElement("td");
var cellText = document.createTextNode(realArrayRequest[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 2){
var cell = document.createElement("td");
//cell.setAttribute("contenteditable");
var cellText = document.createTextNode(msg1ReqType[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cell = document.createElement("td");
var cellText = document.createTextNode('');
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function generateTableResponse(){
var body = document.body;
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for(var i=0; i<msg1Res.length; i++){ //rows
var row=document.createElement("tr");
for (var j=0; j < 3; j++){
if (j === 0){ //columns
var cell = document.createElement("td");
var cellText = document.createTextNode(msg1Res[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 1){
var cell = document.createElement("td");
var cellText = document.createTextNode(realArrayResponse[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 2){
var cell = document.createElement("td");
//cell.setAttribute("contenteditable");
var cellText = document.createTextNode(msg1ResType[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cell = document.createElement("td");
var cellText = document.createTextNode('');
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function parseUserInputReq(){
realArrayRequest=[];
//cleans the array from all previous values entered before running all functions
var input = document.getElementById("userInputRequest").value;
var noBracketsStr=input.split(",");
//pushing results from noBracketsStr into a new array realArray, because it seems that split() does not change the original array(string)
for(var i = 0; i < noBracketsStr.length; i++){
realArrayRequest.push(noBracketsStr[i])
}
generateTableRequest();
}
function parseUserInputRes(){
realArrayResponse=[];
//cleans the array from all previous values entered before running all functions
var input = document.getElementById("userInputResponse").value;
var noBracketsStr=input.split(",");
//pushing results from noBracketsStr into a new array realArray, because it seems that split() does not change the original array(string)
for(var i = 0; i < noBracketsStr.length; i++){
realArrayResponse.push(noBracketsStr[i])
}
generateTableResponse();
}
//Message elements
//Message 1
const msg1Req = ['Login Command', 'version', 'xID', 'passcode', 'machineID', 'equipment Serial Number', 'userSlot', 'clubID', 'loginType'];
const msg1ReqType = ['integer', 'integer', 'string', 'string', 'string', 'string', 'integer', 'integer', 'string'];
const msg1Res = ['Login Command', 'Version', 'Result', 'User token'];
const msg1ResType = ['integer', 'integer', 'integer', 'string'];
#parseCommandRequest {
width: 50%;
float: left;
};
#parseCommandResponse {
width: 50%;
float: left;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
<script defer type="text/javascript" src="index.js" charset="UTF-8"></script>
</head>
<body>
<div id="parseCommandRequest">
<form name="userInputReq">
Request
<input type="text" id="userInputRequest">
<input type="button" value="Parse" onclick="parseUserInputReq()">
</form>
</div>
<div id="parseCommandResponse">
<form name="userInputRes">
Response
<input type="text" id="userInputResponse">
<input type="button" value="Parse" onclick="parseUserInputRes()">
</form>
</div>
</body>
</html>
As you mentioned, there's a lot of different ways to solve this. The most common way to solve problems like this is to use CSS. There's actually a quite easy way to achieve this with the CSS you already have. Instead of injecting the two tables in the body you can inject the tables in #parseCommandRequest and #parseCommandResponse. To do this you simply have to replace body.appendChild(tbl); with code to inject them in the correct divs instead.
This is one possible way to achieve that:
// Replace body.appendChild(tbl); with the following
var parseCommandRequestDiv = document.getElementById("parseCommandRequest");
parseCommandRequestDiv.appendChild(tbl);
// Do the same for the response
var parseCommandResponseDiv = document.getElementById("parseCommandResponse");
parseCommandResponseDiv.appendChild(tbl);
When creating a table with js following the following tutorial:
https://www.aspsnippets.com/Articles/Create-dynamic-Table-in-HTML-at-runtime-using-JavaScript.aspx
I'm getting the unexpected result, the table is creating the elements on the same line as the header, and I can not understand why this is happening if anyone could help me I'd be grateful.
Att,
Carlos Eduardo
//browserify index.js > bundle.js
const request = require('request')
var respRequest
var buttonTable = document.getElementById("button-table").addEventListener("click", function() {
request('https://jsonplaceholder.typicode.com/photos', function(error, response, body) {
console.log('error:', error)
console.log('statusCode:', response && response.statusCode)
//console.log('body:', body)
var content = []
content = JSON.parse(body)
var a = content.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key]
})
})
a.unshift(["AlbumId", "id", "url", "title", "thumbnailUrl"])
var table = document.createElement("table")
table.border = "1"
var columnCount = a[0].length
var row = table.insertRow(-1)
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("th")
headerCell.innerHTML = a[0][i]
row.appendChild(headerCell)
}
for (var i = 1; i < a.length; i++) {
line = table.insertRow(-1)
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1)
cell.innerHTML = a[i][j]
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./css/style.css">
<title>Meu Site</title>
</head>
<body>
<div class="container">
<p>Gerar Relatorio</p>
<button type="button" id="button-table" class="btn btn-default ">Gerar
Relatorio</button>
<div id="dvTable"></div>
</div>
<script src="script/bundle.js"></script>
</body>
</html>
I expect that it will create a table perfectly, with header, and lines, in a way that you can read perfectly what is in the table
var row = table.insertRow(-1)
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("th")
headerCell.innerHTML = a[0][i]
row.appendChild(headerCell)
}
for (var i = 1; i < a.length; i++) {
line = table.insertRow(-1)
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1)
cell.innerHTML = a[i][j]
}
}
In the first loop you create the header-row, stored in variable row.
in the second loop you try to create several more rows in variable line,
but you still append your cells to row.
I want to generate dynamic table with Javascript, want to generate table like this table:
<table>
<tbody>
<tr>
<th>Owner</th>
<th>Number</th>
</tr>
<tr>
<td>aaa</td>
<td> 3 </td>
</tr>
...
</tbody>
</table>
then I write a script to generate the table, but I can't get correct table, I don't know where has problem, could anyone help to check it?
var arrName = ['aaa', 'bbb','ccc'];
var arrNumber = [3, 2, 4];
if (arrName.length != 0 && arrNumber.length != 0)
{
var table = document.createElement('table');
var tbody = document.createElement('tbody');
var tr_header = document.createElement('tr');
var th_owner = document.createElement('th');
var th_number = document.createElement('th');
th_owner.appendChild(document.createTextNode('Owner'));
th_number.appendChild(document.createTextNode('Number'));
tr_header.appendChild(th_owner);
tr_header.appendChild(th_number);
tbody.appendChild(tr_header);
for (var i = 0; i < arrName.length; i++)
{
var tr_details = document.createElement('tr');
var td_owner = document.createElement('td');
var td_count = document.createElement('td');
td_owner.appendChild(document.createTextNode(arrName[i].toString()));
td_count.appendChild(document.createTextNode(arrNumber[i].toString()));
tr_details.appendChild(td_owner);
tr_details.appendChild(td_count);
tbody.appendChild(tr_details);
}
table.appendChild(tbody);
}
}
Your code is working perfectly. Maybe you just missed to add the table to the page.
I just added bellow code to the end:
var body = document.getElementsByTagName('body');
body[0].appendChild(table);
Check the test page I wrote:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', () => {
var arrName = ['aaa', 'bbb','ccc'];
var arrNumber = [3, 2, 4];
if (arrName.length != 0 && arrNumber.length != 0)
{
var table = document.createElement('table');
var tbody = document.createElement('tbody');
var tr_header = document.createElement('tr');
var th_owner = document.createElement('th');
var th_number = document.createElement('th');
th_owner.appendChild(document.createTextNode('Owner'));
th_number.appendChild(document.createTextNode('Number'));
tr_header.appendChild(th_owner);
tr_header.appendChild(th_number);
tbody.appendChild(tr_header);
for (var i = 0; i < arrName.length; i++)
{
var tr_details = document.createElement('tr');
var td_owner = document.createElement('td');
var td_count = document.createElement('td');
td_owner.appendChild(document.createTextNode(arrName[i].toString()));
td_count.appendChild(document.createTextNode(arrNumber[i].toString()));
tr_details.appendChild(td_owner);
tr_details.appendChild(td_count);
tbody.appendChild(tr_details);
}
table.appendChild(tbody);
var body = document.getElementsByTagName('body');
body[0].appendChild(table);
}
});
</script>
</body>
</html>