Update data from a DOM table dynamically - javascript

I'm developing an API, it's been a while and I'm answering several questions here, I really appreciate the community for the help The doubt I have today is in relation to updates, my table is connected to an oracle database, and who is moving all this connection is nodejs, the table is generated by DOM, it's working fine, but now comes the doubt. Is there a way to update her data dynamically? I say with each new data that enters it updates and leaves the most recent on the screen
I programmed a timer to keep refreshing the page, it's the only way it updates, but I wanted to
try to make it dynamic, to stay visually prettier.
What tool would I use to do this?
This is the one, it only updates the data if I refresh the entire page.
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Apontamentos da Produção</title>
<link rel="stylesheet" type="text/css" href="styles.css" media="screen" />
</head>
<body>
<meta http-equiv="refresh" content="5">
<div id="data"></div>
<div class="grid-container">
<div class="container">
<div class="texto"> PAINEL-1 | APONTAMENTOS DA PRODUÇÃO</div>
<div class="clock"></div>
</div>
</div>
<br>
<!-- Table to list data -->
<table id="table" class="tablePrincipal">
<tr class="trPrincipal">
<th class="th2" style="width: 11%;">Data</th>
<th class="th2" style="width: 8%; ">Hora</th>
<th class="th2" style="width: 5%;">Orig.</th>
<th class="th2" style="width: 8%;">O.P.</th>
<th class="th2" style="width: 10%;">Produto</th>
<th class="th2" style="width: 8%;">Deriv.</th>
<th class="th2" style="width: 9%;">Peso (TN)</th>
<th class="th2" style="width: 7%;">Refugo (TN)</th>
<th class="th2" style="width: 13%;">Lote</th>
<th class="th2" style="width: 60%;;">Operador</th>
</tr>
</table>
</body>
<script>
// Here is where the push of information is done, called by localhost and positioning the ID of the table that it will take the information
window.onload = function () {
fetch('http://localhost:3000/teste')
.then(response => response.json())
.then(data => {
console.log(data);
var table = document.getElementById('table');
// First define the variable, and put the command to insert a line, everything is organized by rows
for (var i = 0; i < 7; i++) {
var row = table.insertRow(i + 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
var cell7 = row.insertCell(6);
var cell8 = row.insertCell(7);
var cell9 = row.insertCell(8);
var cell10 = row.insertCell(9);
// Here it calls the variable and places the row in the table
cell1.innerHTML = data[i][0];
cell2.innerHTML = data[i][1];
cell3.innerHTML = data[i][2];
cell4.innerHTML = data[i][3];
cell5.innerHTML = data[i][4];
cell6.innerHTML = data[i][5];
cell7.innerHTML = data[i][6];
cell8.innerHTML = data[i][7];
cell9.innerHTML = data[i][8];
cell10.innerHTML = data[i][9];
}
})
}
</script>
</html>

You can indeed refresh the table using pure JS, using an approach similar to what you're already doing.
Based on your current code variable names, you can take it a few steps further by accessing the rows () and cells () programmatically;
aSpecificTr = table.rows[5];
aSpecificTd = aSpecificTr.cells[3];
Now you can imagine approaches that replace just the content of a specific row, or the content within a cell, even the styling of those elements depending on content (adding color, etc)
In this way you can avoid named variables like var cell1, cell2 and iterate through arrays.
for(let r=0; r<table.rows.length; r++){
let thisRow = table.rows[r];
for(let c=0; c<thisRow.cells.length; c++){
let thisCell = thisRow.cells[c];
}
}
Consider making use of HTML classes. And if your data from the server includes per-row unique identifiers consider integrating that as well.
<tr class='UniqueId-15'>
<td class='Field-Data'>2023-01-16</td>
<td class='Field-Hora'>16:15</td>
</tr>
Also consider using jQuery which could access cells fluently: $('.UniqueId-15 .Field-Hora').html('17:00')
React is alternative you might consider as well, but IMHO your fetch approach + pure JS / jQuery will give you all the power you need to achieve anything you want.

Related

Creating a timetable using JavaScript

I am trying to create a web page where user can create his own schedule. User can enter the values of lines and columns in some input to build a table in which the user will write his schedule. I use this javascript code:
var p = document.getElementById('paragraph');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
for (let i = 0; i < lines; i++){
let tr = document.createElement('tr');
for (let j = 0; j < columns; j++){
let td = document.createElement('td');
}
tbody.appendChild(tr);
}
p.appendChild(table);
However, when I'am trying to add information to table cells, I can't write values to each of them. I've used .innerHTML but it doesn't work the way it needs to. The information will be written only to the beginning of the table.
Should I give id to each td and then address to them by id when I need to write the information? Or there is another way to write values to table cells?
I think you need something like this to insert the data.
We have insertRow(), which is pre-defined function which i used in this answer to insert new row and then inserted columns in it with insertCell function.
<!DOCTYPE html>
<html>
<body>
<div class="inputs">
<input type="text" id="input1" placeholder="Enter first col data" >
<input type="text" id="input2" placeholder="Enter second col data" >
</div>
<br> <br> <br>
<table id="myTable">
<thead style="background-color: beige;">
<tr>
<td>default head row cell 1</td>
<td>default head row cell 2</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button type="button" onclick="myFunction()">add data to body row</button>
<script>
function myFunction() {
var table = document.querySelector("#myTable tbody");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
const val1 = document.getElementById('input1').value;
const val2 = document.getElementById('input2').value;
cell1.innerHTML = val1;
cell2.innerHTML = val2;
}
</script>
</body>
</html>
I think that you need to refer to your button in the js file and write a function that will be executed on the "onclick" event
In this function, you are accessing the table variable. By using the built in javaScript function «insertRow()» you are adding rows to your table. Then you should add cells to this row in which information that users entered will be stored. This you can also do by using build in function «insertCell()»
Next, you access the fields in which the user has entered data
Retrieve values ​​using the «value» built-in function
Using the built-in «innerHTML» function, draw cells with the information that you received in the previous step
You can look at the written code below for better assimilation of information
<!DOCTYPE html>
<html>
<body>
<div class="inputs" >
<input type="text" id="firstColumn" placeholder="Enter data here" >
<input type="text" id="SecondColumn" placeholder="Enter data here" >
</div>
<table id="Table">
<thead>
<tr>
<td style="background-color: pink;">Name of first column</td>
<hr>
<td style="background-color: purple;">Name of second column</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button style="background-color: yellow;" type="button" id = "btn">Add</button>
<script>
const button = document.querySelector('#btn');
btn.onclick = function() {
var table = document.querySelector("#Table tbody");
var row = table.insertRow();
var Fcell = row.insertCell(0);
var Scell = row.insertCell(1);
const Fdata = document.getElementById('firstColumn').value;
const Sdata = document.getElementById('SecondColumn').value;
Fcell.innerHTML = Fdata;
Scell.innerHTML = Sdata;
}
</script>
</body>
</html>

Javascript insert into table using loop

I am working on the below code. The user selects an image and clicks on the data table button. On clicking the button the respective table fields are filled
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = Math.floor(Math.random() * 100);
cell2.innerHTML = document.getElementById('img_add').files[0].name;
cell3.innerHTML = document.getElementById('img_add').files[0].size;
cell4.innerHTML = '<span class="p-viewer"><i class="fa fa-eye" aria-hidden="true"></i></span>';
}
<!DOCTYPE html>
<html>
<head>
<title>Datatable form</title>
</head>
<body>
<div class="container">
<div style="text-align: center;padding-top: 2rem;">
<input type="file" name="file" id="img_add">
<button type="button" onclick="myFunction()">Data Table</button>
</div>
<img>
<div class="col-10 center" style="margin: auto;text-align: center;">
<div class="table-responsive">
<table id="myTable" class="table table-bordered border-primary ">
<thead>
<tr>
<th scope="col">Sr No.</th>
<th scope="col">Image Name</th>
<th scope="col">Image Size (bytes))</th>
<th scope="col">View</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</body>
</html>
I am able to do it line by line but I want to add it via a loop. How to achieve it
Any help would be highly appreciated
Well first you need to create the table data. You should create it as a JSON string. Next you need to call the myFunction() inside a for loop, and pass it the JSON data as parameter. See this description of JSON

How to add rows into HTML table dynamically from the data fetched from external API?

I am new to JavaScript, not sure if this very basic question. I am trying to create a Covid-19 dashboard using the data fetched from the external API. I managed to get the data from the API. I can able to add rows(one by one) from JavaScript without any issues. But, there are around 186 countries, I am not sure how should I push the row data into a HTML table dynamically. I tried to iterate the array but still I am not able to proceed.
I have provided the code snippets below as well as external API from where I am pulling the data.
Please let me know how should I insert the row dynamically into a HTML table for all the countries. Thank you so much in advance.
Current Output: https://i.imgur.com/4wywYmJ.png
External API: https://api.covid19api.com/summary
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="style.css" />
<title>Covid 19 Summary</title>
</head>
<body>
<div class="container">
<h1 class="text-center mt-5">Covid 19 Live Summary in Table format</h1>
<table class="table table-sm table-hover" id="table1">
<thead>
<tr>
<th scope="col">Country</th>
<th scope="col">Total Cases</th>
<th scope="col">Total Deaths</th>
<th scope="col">Total Recovered</th>
</tr>
</thead>
<tbody>
<tr id="data"></tr>
</tbody>
</table>
<br />
<button class="btn btn-info btn-block btn-primary btn-lg" id="refresh">
Refresh Data
</button>
</div>
<script src="app.js"></script>
</body>
</html>
Javascript
window.addEventListener('load', () => {
let api = "https://api.covid19api.com/summary";
let table = document.getElementById("data");
var table1 = document.getElementById("table1");
const refresh = document.getElementById("refresh");
const countries = [];
console.log(table1);
initialize();
function initialize() {
fetch(api).then(response => {
// console.log(response);
return response.json();
}).then(data => {
countries.push(...data.Countries);
console.log(countries);
console.log(countries[1].Country);
for (i = 0; i < countries.length; i++) {
console.log(countries[i]);
}
var row = table1.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = countries[1].Country;
cell2.innerHTML = countries[1].TotalConfirmed;
cell3.innerHTML = countries[1].TotalDeaths;
cell4.innerHTML = countries[1].TotalConfirmed;
}
);
}
refresh.addEventListener('click', () => {
table.innerHTML = '';
initialize();
})
});
CSS:
#import url("https://fonts.googleapis.com/css2?family=Oswald:wght#400;700&display=swap");
tr,
td {
text-align: center;
}
body {
font-family: "Oswald", sans-serif;
}
Iterating over the countries works fine.
Try this:
function initialize() {
fetch(api)
.then(response => {
// console.log(response);
return response.json();
})
.then(data => {
countries.push(...data.Countries);
console.log(countries);
console.log(countries[1].Country);
for (var i = 0; i < countries.length; i++) {
var country = countries[i];
var row = table1.insertRow(-1); // -1 to append at end of table
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = country.Country;
cell2.innerHTML = country.TotalConfirmed;
cell3.innerHTML = country.TotalDeaths;
cell4.innerHTML = country.TotalConfirmed;
}
});
}

Javascript function not working in jsp page

I want to use a javascript in my jsp page in order to insert value of the input box into a table row.
My Jsp Page:-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Title</title>
<script type="text/javascript">
function addData(){
var x = 1;
var a = document.getElementById('area').value;
var table = document.getElementByTagName('table')[0];
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = x++;
cell2.innerHTML = a;
}
</script>
</head>
<body>
<h2>Area...</h2>
Area: <input type="text" id="area" name="area" required/><label>sq. ft.
<button onclick="addData();">Add To Table</button>
</br></br>
<div>
<h2>Area Table...</h2>
<table border="1">
<tr>
<th>Section</th>
<th>Area</th>
</tr>
<tr>
<td>1</td>
<td>125.4485</td>
</tr>
</table>
</div>
</body>
</html>
Here i wanted to insert a row into a table from the input box. But the value is not being inserted.
Is there any problem in the code.
use the console developer tools of your browser, to see errors,
here is the error :
Uncaught TypeError: document.getElementByTagName is not a function
at addData (a.html:11)
at HTMLButtonElement.onclick (a.html:28)
which means javascript doesn't recognise this function , so you have to look , the right notation of the function which is
getElementsByTagName
Please correct the spelling getElementByTagName to getElementsByTagName
Typo
Try like this, TagName is the multiple selector.you are missing s
var table = document.getElementsByTagName('table')[0];
instead of
var table = document.getElementByTagName('table')[0];
function addData() {
var x = 1;
var a = document.getElementById('area').value;
var table = document.getElementsByTagName('table')[0];
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = x++;
cell2.innerHTML = a;
}
<h2>Area...</h2>
Area: <input type="text" id="area" name="area" required/><label>sq. ft.
<button onclick="addData();">Add To Table</button>
</br></br>
<div>
<h2>Area Table...</h2>
<table border="1">
<tr>
<th>Section</th>
<th>Area</th>
</tr>
<tr>
<td>1</td>
<td>125.4485</td>
</tr>
</table>
</div>

How to add edit and remove buttons to each row table dynamically

I want to add edit and remove buttons in the third row of the table below whenever a row is added to the table. When the user user click edit, the columns cells becomes editable based on their original type (text-box and drop-down menu) and allow editing. In addition, the edit button adds a new save button after the user clicks the edit button. When the user clicks delete, the row gets deleted. I have seen a lot of previous posts but I want to use HTML and Javascript-only unless if it is not possible at all (some solutions recommend external libraries and some use JQuery).
I tried several ways with no success. I will be thankful to any pointer or code snippet that simplifies this task for me.
I have a database where I get and store data to but I am simplifying the code with arrays as follows.
HTML:
<html>
<head>
<meta charset="UTF-8">
</head>
<body id="body">
<div id="wrapper">
<table align='center' cellspacing=1 cellpadding=1 id="mytable" border=1>
<tr>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
<tr>
<td><input type="text" id="text"></td>
<td>
<select name="levels" id="levels">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" id="add-button" value="Add"></td>
</tr>
</table>
</div>
<script src="get-text.js"></script>
</body>
</html>
Script:
var myArray = [{"name":"aaa","level":"A"},{"name":"bbb","level":"B"},{"name":"ccc","level":"C"}];
//to display stored data in the table
function display()
{
var table=document.getElementById("mytable");
var length=myArray.length;
for(var i=0; i<length; i++)
{
var row = table.insertRow(i+1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = myArray[i].name;
cell2.innerHTML = myArray[i].level;
}//end for
} //end display
display(); //call display.
var addButton=document.getElementById("add-button");
//listen to add button. If clicked, store the entered data and append them in the display
addButton.addEventListener('click', function (){
event.preventDefault();
//get the data from the form
var mytext = document.getElementById("text").value;
var mylevel = document.getElementById("levels").value;
//store the entered values into the array
myArray.name=mytext;
myArray.level=mylevel;
var length=myArray.length;
console.log("Array Length: "+length)
//add the entered data to the table.
var table=document.getElementById("mytable");
var newRow = table.insertRow(length+1);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
cell1.innerHTML = mytext;
cell2.innerHTML = mylevel;
mytext.value = '';
}, false);
EDIT:
I am trying to something like this in my code. Add, Edit, Delete from Tables Dynamically but my attempts were not successful in this part.
Full working code:
<html>
<head>
<meta charset="UTF-8">
</head>
<body id="body">
<div id="wrapper">
<table align='center' cellspacing=1 cellpadding=1 id="mytable" border=1>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<button onclick='display()'> Display</button>
<!--<script src="get-text.js"></script>-->
</body>
</html>
<script>
var myArray = [{ "name": "aaa", "level": "A" }, { "name": "bbb", "level": "B" }, { "name": "ccc", "level": "C" }];
function display() {
var length = myArray.length;
var htmltext = "";
for (var i = 0; i < length; i++) {
console.log(myArray[i]);
htmltext += "<tr id='table"+i+"'><td>"
+myArray[i].name+
"</td><td>"
+myArray[i].level+
"</td><td><button onclick='edit("+i+")'>Edit</button><button onclick='remove("+i+")'>Remove</button></td></tr>";
}
document.getElementById("tbody").innerHTML = htmltext;
}
function edit(indice) {
var htmltext = "<tr><td><input id='inputname"+indice+"' type='text' value='"
+myArray[indice].name+
"'></td><td><input id='inputlevel"+indice+"' type='text' value='"
+myArray[indice].level+
"'></td><td><button onclick='save("+indice+")'>Save</button><button onclick='remove("+indice+")'>Remove</button></td></tr>";
document.getElementById("table"+indice).innerHTML = htmltext;
}
function save(indice) {
myArray[indice].name = document.getElementById("inputname"+indice).value;
myArray[indice].level = document.getElementById("inputlevel"+indice).value;
var htmltext = "<tr id='table"+indice+"'><td>"
+myArray[indice].name+
"</td><td>"
+myArray[indice].level+
"</td><td><button onclick='edit("
+indice+")'>Edit</button><button onclick='remove("
+indice+")'>Remove</button></td></tr>";
document.getElementById("table"+indice).innerHTML = htmltext;
}
function remove(indice) {
console.log(myArray);
myArray.splice(indice, 1);
display();
}
</script>

Categories

Resources