Javascript insert into table using loop - javascript

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

Related

Update data from a DOM table dynamically

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.

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

Adding elements with JavaScript

I want to add a new row to a table. Therefore I have tried it in two different ways. In my opinion both should work. But indeed the don't. The first approach does not work. But why?
First approach (not working...):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Table</title>
<script type="text/javascript">
function addLine(nr, name, date) {
var neueZeile = document.createElement("tr");
var neuerEintrag1 = document.createElement("td");
var neuerText1 = document.createTextNode(nr);
var neuerEintrag2 = document.createElement("td");
var neuerText2 = document.createTextNode(name);
var neuerEintrag3 = document.createElement("td");
var neuerText3 = document.createTextNode(date);
neuerEintrag1.appendChild(neuerText1);
neuerEintrag2.appendChild(neuerText2);
neuerEintrag3.appendChild(neuerText3);
neueZeile.appendChild(neuerEintrag1);
neueZeile.appendChild(neuerEintrag2);
neueZeile.appendChild(neuerEintrag3);
var parentN = document.getElementById("myTable");
parentN.appendChild(neueZeile);
</script>
<link rel="stylesheet" type="text/css" href="Website.css" />
</head>
<body>
<table class="table" id="myTable">
<thead>
<td>Nr.</td>
<td>Name</td>
<td>Datum</td>
</thead>
<tr>
<td>1</td>
<td>Max</td>
<td>01.01.2001</td>
</tr>
</table>
<form name=addRow>
Nr.:
<input type=text name=btn1>
Name:
<input type=text name=btn2>
Date:
<input type=text name=btn3>
<input type=button name=btn4 value=ADD
onclick="addLine(btn1.value,btn2.value,btn3.value)">
</form>
<input type=button name=btn5 value=DeleteLastAddedRow onclick="deleteRow()">
<a class="back" href="Website.html">Zurück</a>
</body>
</html>
My approach is not working. Does somebody know why or can help me?
Second approach (works fine...):
function addLine(nr, name, date) {
var table = document.getElementById("myTable");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = nr;
cell2.innerHTML = name;
cell3.innerHTML = date;
}
I am really interested in why the the first approach is not working.
Does somebody have an idea?
Kind regards
You missed to create tr element. Create tr and append it to table then all td to new tr.
Here is working code
function addLine(nr, name, date) {
var neuerEintrag1 = document.createElement("td");
var neuerText1 = document.createTextNode(nr);
var neuerEintrag2 = document.createElement("td");
var neuerText2 = document.createTextNode(name);
var neuerEintrag3 = document.createElement("td");
var neuerText3 = document.createTextNode(date);
neuerEintrag1.appendChild(neuerText1);
neuerEintrag2.appendChild(neuerText2);
neuerEintrag3.appendChild(neuerText3);
var parentN = document.getElementById("myTable");
var row = document.createElement("tr");
parentN.appendChild(row);
row.appendChild(neuerEintrag1);
row.appendChild(neuerEintrag2);
row.appendChild(neuerEintrag3);
}
<table class="table" id="myTable">
<thead>
<td>Nr.</td>
<td>Name</td>
<td>Datum</td>
</thead>
<tr>
<td>1</td>
<td>Max</td>
<td>01.01.2001</td>
</tr>
</table>
<form name=addRow>
Nr.:
<input type=text name=btn1> Name:
<input type=text name=btn2> Date:
<input type=text name=btn3>
<input type=button name=btn4 value=ADD onclick="addLine(btn1.value,btn2.value,btn3.value)">
</form>

Dynamically insert table values based upon input?

Based upon user-input I want to generate a matrix / table for display. Here is the html
html
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>lostBondUserPmtEntry</title>
<body>
<form name="test" ><font face="Verdana" size = "2">
<input name="Text1" type="text" /> score <br>
<input type="submit" Name ="test" id="gp"/>
<input type="hidden" name="dateFactor">
<table border="1">
<tr>
<td>sensitivity level</td>
<td>criticality level</td>
<td>priority level</td>
<td>Response time</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>high</td>
<td>2 hours</td>
</tr>
</table>
</form>
</body>
DEMO
The brief algo is
if score is 10 (certain value) populate the table as with predefined values (those values with column names are shown in DEMO). I want the table to be generated on particular button. I can call function, but I want to know how to append the html code for table on function call.
Thanks.
To append a row to the table you can try something like this:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = "cell 1 text";
var cell2 = row.insertCell(1);
cell2.innerHTML = "cell 2 text";
var cell3 = row.insertCell(2);
cell3.innerHTML = "cell 3 text";
}

Categories

Resources