Adding a new row to table using Javascript - javascript

When the user clicks the add new button a new row should be added to the bottom of the table, but when I click the button, nothing happens. The script looks fine to me and I've tried to find a solution for hours.
function addRow(tableID) {
var table = document.getElementById(tableID),
row = tbl.insertRow(tbl.rows.length),
i;
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
<head>
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<table id="countries">
<thead>
<tr>
<th>Country</td>
<th>Code</td>
</tr>
</thead>
<tbody>
<tr>
<td>Algeria</td>
<td>213</td>
</tr>
</tbody>
</table>
<button type="button" onclick="addRow('countries');">Add New</button>
</body>

You can try this :
function addRow(tableID) {
var table = document.getElementById(tableID),
row = table.insertRow(table.rows.length),
i;
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'),
txt = document.createTextNode(text);
div.appendChild(txt);
div.setAttribute('class', style);
div.setAttribute('className', style);
cell.appendChild(div);
}
<html>
<title>Test</title>
<head>
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<table id="countries">
<thead>
<tr>
<th>Country</td>
<th>Code</td>
</tr>
</thead>
<tbody>
<tr>
<td>Algeria</td>
<td>213</td>
</tr>
</tbody>
</table>
<button type="button" onclick="addRow('countries');">Add New</button>
</body>
</html>

You can done this with very little code using JQuery. check below code here :-
$(document).ready(function(){
$(".add").click(function(){
$("#countries tbody tr:last-child").after("<tr><td>Data</td><td>data</td></tr>")
});
});
table, th, td{
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="countries">
<thead>
<tr>
<th>Country</th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>Algeria</td>
<td>213</td>
</tr>
</tbody>
</table>
<button class="add" type="button">Add New</button>

I hope that this is what you are looking for,
<script>
function addRow(tableID) {
var table = document.getElementById(tableID); // get tableById
var rowCount = table.rows.length; // get row count
var cellCount = table.rows[0].cells.length; // get cell count
var row = table.insertRow(rowCount); // create row
for(var i =0; i <= cellCount; i++){
createCell(row.insertCell(i), i, 'row');
}
}
</script>

Related

Moving data from one html table to another

I am struggling with something that should be so simple.
I am trying to move a row from one html table to another, basically a table with selection options and input to another table with the final selections and values.
Image for UI
My Html code is as follow,
function GetIndex()
{
var table = document.getElementById("table1");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
console.log("HERE " + id );
localStorage.setItem("ID", id);
};
};
currentRow.onclick = createClickHandler(currentRow);
AddNextTable();
}
}
function AddNextTable()
{
var ID= localStorage.getItem("ID");
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2");
var table = document.getElementById("table1");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
var Counter= 0;
Counter++;
var InputSelect= "input" + ID;
console.log(InputSelect);
var NewText= document.getElementById(InputSelect).value;
var newRow = table2.insertRow(table2.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
cell1.innerHTML = table1.rows[id].cells[0].innerHTML;
cell2.innerHTML = table1.rows[id].cells[1].innerHTML;
cell3.innerHTML = table1.rows[id].cells[2].innerHTML;
cell4.innerHTML = "<input type='checkbox' name='check-tab2'>";
cell3.innerHTML= "<input type='text' value="+ NewText+ ">"
var index = table1.rows[1].rowIndex;
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
function tab2_To_tab1()
{
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2"),
checkboxes = document.getElementsByName("check-tab2");
console.log("Val1 = " + checkboxes.length);
for(var i = 0; i < checkboxes.length; i++)
if(checkboxes[i].checked)
{
// create new row and cells
var newRow = table1.insertRow(table1.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
// add values to the cells
cell1.innerHTML = table2.rows[i+1].cells[0].innerHTML;
cell2.innerHTML = table2.rows[i+1].cells[1].innerHTML;
cell3.innerHTML = table2.rows[i+1].cells[2].innerHTML;
cell4.innerHTML = "<input type='checkbox' name='check-tab1'>";
// remove the transfered rows from the second table [table2]
var index = table2.rows[i+1].rowIndex;
table2.deleteRow(index);
// we have deleted some rows so the checkboxes.length have changed
// so we have to decrement the value of i
i--;
console.log(checkboxes.length);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Transfer Rows Between Two HTML Table</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container{overflow: hidden}
.tab{float: left}
.tab-btn{margin: 50px;}
button{display:block;margin-bottom: 20px;}
tr{transition:all .25s ease-in-out}
tr:hover{background-color: #ddd;}
</style>
</head>
<body>
<div class="container">
<div class="tab">
<table id="table1" border="1">
<tr>
<th>Code</th>
<th>Name</th>
<th>Amount</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>
<input type="text" id="input1">
</td>
<td>
<button onclick="GetIndex()">Add</button>
</td>
</tr>
<tr>
<td>2</td>
<td>Dean</td>
<td><input type="text" id="input2"></td>
<td>
<button onclick="GetIndex()">Add</button>
</td>
</tr>
<tr>
<td>3</td>
<td>Fred</td>
<td><input type="text" id="input3"></td>
<td>
<button onclick="GetIndex()">Add</button>
</td>
</tr>
</table>
</div>
<div class="tab">
<table id="table2" border="1">
<tr>
<th>Code</th>
<th>Name</th>
<th>Action</th>
<th>Action</th>
</tr>
</table>
</div>
</div>
</body>
<script src="main.js"></script>
</html>
My end goal will be for the user to enter a certain amount of an item in the first table, and have it display in the next. I am looping through something incorrectly somewhere.
I found it quite complicated about your code. Just why not giving it a param that describes which button/input called the function? It will be much easier and also this will no longer require the use of localStorage. Hope this solves your problem.
On the html:
<button onclick="GetIndex('input1')"></button>
On the js
function GetIndex(src) {
...
AddIndex(src);
...
}
function AddIndex(src) {
...
var ID = src;
...
}
function GetIndex(src)
{
var table = document.getElementById("table1");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
console.log("HERE " + id );
localStorage.setItem("ID", id);
};
};
currentRow.onclick = createClickHandler(currentRow);
AddNextTable(src);
}
}
function AddNextTable(src)
{
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2");
var table = document.getElementById("table1");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
var Counter= 0;
Counter++;
var InputSelect= src;
console.log(InputSelect);
var NewText= document.getElementById(InputSelect).value;
var newRow = table2.insertRow(table2.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
cell1.innerHTML = table1.rows[id].cells[0].innerHTML;
cell2.innerHTML = table1.rows[id].cells[1].innerHTML;
cell3.innerHTML = table1.rows[id].cells[2].innerHTML;
cell4.innerHTML = "<input type='checkbox' name='check-tab2'>";
cell3.innerHTML= "<input type='text' value="+ NewText+ ">"
var index = table1.rows[1].rowIndex;
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
function tab2_To_tab1()
{
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2"),
checkboxes = document.getElementsByName("check-tab2");
console.log("Val1 = " + checkboxes.length);
for(var i = 0; i < checkboxes.length; i++)
if(checkboxes[i].checked)
{
// create new row and cells
var newRow = table1.insertRow(table1.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
// add values to the cells
cell1.innerHTML = table2.rows[i+1].cells[0].innerHTML;
cell2.innerHTML = table2.rows[i+1].cells[1].innerHTML;
cell3.innerHTML = table2.rows[i+1].cells[2].innerHTML;
cell4.innerHTML = "<input type='checkbox' name='check-tab1'>";
// remove the transfered rows from the second table [table2]
var index = table2.rows[i+1].rowIndex;
table2.deleteRow(index);
// we have deleted some rows so the checkboxes.length have changed
// so we have to decrement the value of i
i--;
console.log(checkboxes.length);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Transfer Rows Between Two HTML Table</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container{overflow: hidden}
.tab{float: left}
.tab-btn{margin: 50px;}
button{display:block;margin-bottom: 20px;}
tr{transition:all .25s ease-in-out}
tr:hover{background-color: #ddd;}
</style>
</head>
<body>
<div class="container">
<div class="tab">
<table id="table1" border="1">
<tr>
<th>Code</th>
<th>Name</th>
<th>Amount</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>
<input type="text" id="input1">
</td>
<td>
<button onclick="GetIndex('input1')">Add</button>
</td>
</tr>
<tr>
<td>2</td>
<td>Dean</td>
<td><input type="text" id="input2"></td>
<td>
<button onclick="GetIndex('input2')">Add</button>
</td>
</tr>
<tr>
<td>3</td>
<td>Fred</td>
<td><input type="text" id="input3"></td>
<td>
<button onclick="GetIndex('input3')">Add</button>
</td>
</tr>
</table>
</div>
<div class="tab">
<table id="table2" border="1">
<tr>
<th>Code</th>
<th>Name</th>
<th>Action</th>
<th>Action</th>
</tr>
</table>
</div>
</div>
</body>
<script src="main.js"></script>
</html>
I think you're overcomplicating.
You don't need localStorage, you don't need almost anything. Just a bit of JS .append() to move back and forth your rows. Than using CSS you can additionally pimp the desired items to show/hide or even the button text:
const moveTR = (ev) => {
const EL_tr = ev.currentTarget.closest("tr");
const sel = EL_tr.closest("table").id === "table1" ? "#table2" : "#table1";
document.querySelector(sel + " tbody").append(EL_tr);
};
document.querySelectorAll("table button")
.forEach(EL => EL.addEventListener("click", moveTR));
table {border-collapse: collapse;}
th, td {border: 1px solid #ddd; padding: 5px 10px;}
#table1 button::after {content: "Add"}
#table2 button::after {content: "\2715"}
<table id="table1">
<thead>
<tr><th>Code</th><th>Name</th><th>Amount</th><th>Action</th></tr>
</thead>
<tbody>
<tr>
<td>8</td><td>Fred</td><td><input type="text"></td>
<td><button type="button"></button></td>
</tr>
<tr>
<td>4</td><td>Dean</td><td><input type="text"></td>
<td><button type="button"></button></td>
</tr>
<tr>
<td>1</td><td>Mark</td><td><input type="text"></td>
<td><button type="button"></button></td>
</tr>
</tbody>
</table>
<table id="table2">
<thead>
<tr><th>Code</th><th>Name</th><th>Amount</th><th>Action</th></tr>
</thead>
<tbody>
</tbody>
</table>

Change inner txt of table

I have a table with names, surnames and etc. I should change the value of the clicked td using input. I managed to changed the value of the first td but I am not sure how can change the values of specific td.
Here is my code.
let inp
let changevalue
let click = addEventListener("focus" ,function(){
changevalue = document.querySelector("td")
inp = document.createElement("input")
inp.value = changevalue.innerHTML
changevalue.innerHTML = " "
changevalue.append(inp)
})
let newclick = addEventListener("blur" , function(){
changevalue.innerHTML = inp.value
})
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style="width:100%" id = "TB">
<tr >
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr >
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>
You can add click event listeners on each td element and use the blur event only for the dynamically created input.
const tds = document.querySelectorAll("#TB td");
tds.forEach(td => {
td.addEventListener("click", e=>{
let inp = document.createElement("input")
inp.value = td.innerHTML
td.innerHTML = " "
td.append(inp);
inp.focus();
inp.addEventListener("blur", e=>{
td.innerHTML = inp.value;
});
});
});
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style="width:100%" id = "TB">
<tr >
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr >
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>

Delete Dynamic HTML table using table id?

I'm creating multiple tables from one table (table id = table6)
If I created a new table from table id ='table6', I want to delete that newly generated table using its table id. I have assigned table ids to the newly generated tables. what's wrong in my code?
I want to delete this HTML table. Any hint?
var aggTableNum = 0;
function generateAgg() {
const originTable = document.getElementById('table6');
const baseRowTbl = originTable.querySelector('tbody tr');
let newTable = originTable.cloneNode(true);
let newTbody = newTable.querySelector('tbody');
newTable.id = 'newAggTable' + ++aggTableNum;
// for (i = 0; i < 0; i++) {
// newTbody.appendChild(baseRowTbl.cloneNode(true));
// }
newTable.querySelectorAll('input').forEach((element) => {
element.value = '';
});
document.body.appendChild(newTable);
}
function tID() {
$('table').on('click', 'button', function (e) {
alert(e.delegateTarget.id);
var tbl = e.delegateTarget.id;
console.log(tbl);
// if (tbl) tbl.parentNode.removeChild(tbl);
$(tbl).remove();
});
}
table {
border-collapse: collapse;
margin: 1em;
}
thead {
background-color: lightblue;
}
td,
th {
border: solid grey 1px;
padding: 1em;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button style="margin: 1%" onclick="generateAgg()">Generate New Table</button>
<table id="table6">
<thead>
<th colspan="6">Table</th>
<tr>
<th> Column 1 </th>
<th> Column 2 </th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input>
</input>
</td>
<td><input>
</input></td>
</tr>
<tr>
<td>
<button style="margin: 1%" onclick="tID()">delete </button>
</td>
</tr>
</tbody>
</table>
JsFiddle link - > https://jsfiddle.net/shreekantbatale2/hn0286zd/8/
Though you are getting the table id's value, need to refer that properly with jquery with a leading # in the selector.
Change this:
$(tbl).remove();
...to:
$('#' + tbl).remove();
Then the table removes.

Adding HTML table rows and columns using Javascript Array , not working

I am working with HTML table and JS array. I have table header and last row of Subtotal.
I have tried to create and add rows with the code below but it's not working. The code should read the array elements and should create rows as per the number of elements and then add columns to it as well.
Help me please!
var titles = ["Book 1","Book 2","Book 3"];
var quantities = [3,1,2];
var prices = [80,125,75];
var GrandTotal = 0;
function myTable() {
for(var i=0;i<titles.length;i++){
var x = document.createElement("TR");
x.setAttribute("id", "myTr[i]");
document.getElementById("table").appendChild(x);
for(var j=0;titles.length;j++){
//creating Title columns
var titleColumn = document.createElement("TD");
var titleColumnText = document.createTextNode(titles[j]);
//adding title values
titleColumn.appendChild(titleColumnText);
document.getElementById("myTr[i]").appendChild(titleColumn);
//creating Quantity columns
var qtyColumn = document.createElement("TD");
var qtyColumnText = document.createTextNode(quantities[j]);
//adding Quantity values
qtyColumn.appendChild(qtyColumnText);
document.getElementById("myTr[i]").appendChild(qtyColumn);
//creating Price columns
var priceColumn = document.createElement("TD");
var priceColumnText = document.createTextNode(prices[j]);
//adding Price values
priceColumn.appendChild(priceColumnText);
document.getElementById("myTr[i]").appendChild(priceColumn);
// Amount calculation
var amt=prices[j]*quantities[j];
//creating Amt columns
var amtColumn = document.createElement("TD");
var amtColumnText = document.createTextNode(amt);
//adding Amt values
priceColumn.appendChild(amtColumnText);
document.getElementById("myTr[i]").appendChild(amtColumn);
GrandTotal += amt;
}
}
}
document.getElementById("grandTotal").innerHTML= GrandTotal;
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Table and Array</title>
<style>
table{
border: 1px solid black;
border-collapse: collapse;
}
th, tr, td{
border: 1px solid black;
}
</style>
</head>
<body ">
<div class="title">
<h1>My Store</h1>
</div>
<table class="table-fill" id="table">
<thead>
<tr>
<th colspan="2">Product Title</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">I want to add rows anc columns here dynamically</td>
</tr>
<tr class="totals">
<td colspan="4" id="subTotal">Subtotal</td>
<td id="grandTotal"></td>
</tr>
</tbody>
</table>
<script src="js/data.js" type="text/JavaScript"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Table and Array</title>
<style>
table{
border: 1px solid black;
border-collapse: collapse;
}
th, tr, td{
border: 1px solid black;
}
</style>
</head>
<body ">
<div class="title">
<h1>My Store</h1>
</div>
<table class="table-fill" id="table">
<thead>
<tr>
<th colspan="2">Product Title</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">I want to add rows anc columns here dynamically</td>
</tr>
<tr class="totals">
<td colspan="4" id="subTotal">Subtotal</td>
<td id="grandTotal"></td>
</tr>
</tbody>
</table>
</body>
<script>
var titles = ["Book 1","Book 2","Book 3"];
var quantities = [3,1,2];
var prices = [80,125,75];
var GrandTotal = 0;
function myTable() {
console.log('a')
for(var i=0;i<titles.length;i++){
var x = document.createElement("TR");
x.setAttribute("id", `${titles[i]}`);
document.getElementById("table").appendChild(x);
console.log(document.getElementById("table"))
//creating Title columns
var titleColumn = document.createElement("TD");
var titleColumnText = document.createTextNode(titles[i]);
//adding title values
titleColumn.appendChild(titleColumnText);
console.log(document.getElementById(`${titles[i]}, ${titles[i]}`))
document.getElementById(`${titles[i]}`).appendChild(titleColumn);
//creating Quantity columns
var qtyColumn = document.createElement("TD");
var qtyColumnText = document.createTextNode(quantities[i]);
//adding Quantity values
qtyColumn.appendChild(qtyColumnText);
document.getElementById(`${titles[i]}`).appendChild(qtyColumn);
//creating Price columns
var priceColumn = document.createElement("TD");
var priceColumnText = document.createTextNode(prices[i]);
//adding Price values
priceColumn.appendChild(priceColumnText);
document.getElementById(`${titles[i]}`).appendChild(priceColumn);
// Amount calculation
var amt=prices[i]*quantities[i];
//creating Amt columns
var amtColumn = document.createElement("TD");
var amtColumnText = document.createTextNode(amt);
//adding Amt values
amtColumn.appendChild(amtColumnText);
document.getElementById(`${titles[i]}`).appendChild(amtColumn);
GrandTotal += amt;
}
}
myTable();
var grandTotalText = document.createTextNode(GrandTotal);
document.getElementById("grandTotal").appendChild(grandTotalText)
</script>
</html>

Javascript - How to sum value of every row after press submit button

How to sum value of every row after each submit button event.
I need to calculate the total value of <td> .
Currently the code is calculating total table row.
function myFunction() {
var x = document.getElementById("myTable").rows[0].cells.length;
document.getElementById("demo").innerHTML = x ;
}
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>52</td>
<td>52</td>
<td>12</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
Get all the td iterate over them and add the textContent of the td. Convert the string to number
function myFunction() {
var sum = 0;
document.querySelectorAll('td').forEach(e => sum += +e.textContent)
console.log(sum)
}
<html>
<head>
<style>
table,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>52</td>
<td>52</td>
<td>12</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
You need to loop over your cells. One way you could loop over your cells collection is by using .reduce if you firstly spread your cells into an array using the spread syntax (...). Then, you can use .reduce with destructuring assignment to add up the numbers within each table data element.
See example below:
const displaySum = _ => {
const cells = [...document.getElementById("myTable").rows[0].cells],
sum = cells.reduce((total, {textContent:num}) => +num + total, 0)
document.getElementById("demo").textContent = sum;
}
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>52</td>
<td>52</td>
<td>12</td>
</tr>
</table>
<br>
<button onclick="displaySum()">Try it</button>
<p id="demo"></p>
</body>
</html>
With the least change to your code I use querySelectorAll and convert to number using +
JS<2015 since OP is likely new to JS
function myFunction() {
var sum = 0, cells = document.querySelectorAll("#myTable td");
// all browsers understand a for loop
for (var i=0; i<cells.length; i++) {
sum += +cells[i].innerText;
}
document.getElementById("demo").innerText = sum
}
table,
td {
border: 1px solid black;
}
<table id="myTable">
<tr>
<td>52</td>
<td>52</td>
<td>12</td>
</tr>
</table>
<br>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
Same but in newer JS - no need to reduce
function myFunction() {
var sum = 0, cells = document.querySelectorAll("#myTable td");
cells.forEach(cell => sum += +cell.innerText);
document.getElementById("demo").innerText = sum
}
table,
td {
border: 1px solid black;
}
<table id="myTable">
<tr>
<td>52</td>
<td>52</td>
<td>12</td>
</tr>
</table>
<br>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
Convert .cells to array using Array.from() and use reduce() to add the textContent of each cell.Make sure to convert the textContent to number using Number() or Unary Plus +
function myFunction() {
var cells = Array.from(document.getElementById("myTable").rows[0].cells);
let x = cells.reduce((ac,{textContent}) => Number(textContent) + ac,0);
document.getElementById("demo").innerHTML = x ;
}
function myFunction() {
var cells = document.getElementById("myTable").rows[0].cells
let sum = 0;
for(let i = 0;i<cells.length;i++){
sum += +cells[i].textContent
}
document.getElementById("demo").innerHTML = sum
}
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr><td>52</td><td>52</td><td>12</td></tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
If you want a simple way using no advanced methods. You can use
function myFunction() {
var cells = document.getElementById("myTable").rows[0].cells
let sum = 0;
for(let i = 0;i<cells.length;i++){
sum += +cells[i].textContent
}
document.getElementById("demo").innerHTML = sum
}

Categories

Resources