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
}
Related
This question already has answers here:
Generate HTML table from 2D JavaScript array
(17 answers)
Closed 11 months ago.
I want to display array values in my table rows which I am getting from input values. I create a getting a array but doesn't get idea how can I display them in table?
I want to add more values in same array when I am adding it
also I want to delete table row by clicking on delete at same time its need to be delete from array
this is my code
var users = [
[1, "Yuvraj"],
[2, "Shweta"],
[3, "Namita"],
[4, "Tanvi"]
]
$(document).ready(loadTable);
function loadTable() {
for (var i = 0; i < users.length; i++) {
for (var j = 0; j < users[i].length; j++) {
console.log(users[i][j])
}
}
}
$("#submit").on('click', function() {
var temp = [document.getElementById("id").value, document.getElementById("name").value]
users.push(temp)
loadTable();
});
<html><head><title>Hello</title>table,
th,
td {
border: 1px solid black;
}
<html>
<head>
<title>Hello</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<input type="text" name="id" id="id">
<input type="text" name="name" id="name">
<button type="button" id="submit">Add</button>
<table id="demo">
<tbody>
</tbody>
</table>
</body>
</html>
<html>
<head>
<title>Hello</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<input type="text" name="id" id="id">
<input type="text" name="name" id="name">
<button type="button" id="submit">Add</button>
<table id="demo">
<tbody>
</tbody>
</table>
</body>
</html>
<script>
var users = [[1, "Yuvraj"], [2, "Shweta"], [3, "Namita"], [4,"Tanvi"]]
$(document).ready(loadTable);
function loadTable() {
for(var i = 0; i < users.length; i++){
for(var j = 0; j < users[i].length; j++){
console.log(users[i][j])
}
}
}
$("#submit").on('click', function() {
var temp = [document.getElementById("id").value, document.getElementById("name").value]
users.push(temp)
loadTable();
});
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
Output I am getting
This piece code will empty the #demo table and will fill it with as many rows as many users there are in the users array:
$('#demo tbody').empty();
users.forEach(
user => $('#demo tbody').append(`<tr><td>${user[0]}</td><td>${user[1]}</td></tr>`)
);
You can try the below code. Hope it helps
var users = [
[1, "Yuvraj"],
[2, "Shweta"],
[3, "Namita"],
[4, "Tanvi"]
]
$(document).ready(loadTable);
let outputHTML = ``
function loadTable() {
for (var i = 0; i < users.length; i++) {
outputHTML += `<tr>
<td>${users[i][0]}</td>
<td>${users[i][1]}</td>
<tr>`
}
$('#demo tbody').append(outputHTML);
}
function addItems(item) {
$('#demo tbody').append(`<tr>
<td>${item[0]}</td>
<td>${item[1]}</td>
<tr>`);
}
$("#submit").on('click', function() {
var temp = [document.getElementById("id").value, document.getElementById("name").value]
addItems(temp)
});
table,
th,
td {
border: 1px solid black;
}
<html>
<head>
<title>Hello</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<input type="text" name="id" id="id">
<input type="text" name="name" id="name">
<button type="button" id="submit">Add</button>
<table id="demo">
<tbody>
</tbody>
</table>
</body>
</html>
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>
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>
I am trying to add an alert to notify the user that data has already been entered. I want to apply this to the flight number only. So that when a user types in an already typed flight number and saves it into the array it will pop up a message telling them that it has already been posted.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>
I am also trying to highlight the member table to show which group they are in based on total miles. I would like for the color of the highlight to match the member level. Something kind of like this:
<style>
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
function highlightWeightClass(total-miles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = total-miles< 10000 ? "bronze" : "";
rows[1].className = total-miles >= 10000 && total-miles < 25000 ? "silver" : "";
rows[2].className = total-miles >= 25000 ? "gold" : "";
</script>
For checking if an Array contains on Object, use this:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
For highlighting the member table: add an event listener for document.getElementById("Miles")'s keyup and execute your function then.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
Array.prototype.contains = function(obj) {//function to check if an Array contains an object
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
function highlightWeightClass(totalmiles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = totalmiles< 10000 ? "bronze" : "";
rows[1].className = totalmiles >= 10000 && totalmiles < 25000 ? "silver" : "";
rows[2].className = totalmiles >= 25000 ? "gold" : "";
}
</script>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
if(!FlightNumber.contains(FlightNumberValue)){
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
} else {
alert("You have already entered this flight number.");
}
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
window.onload = function(){
document.getElementById("Miles").addEventListener("keyup", function(event){
highlightWeightClass(document.getElementById("Miles").value);
});
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>
I have been trying to take values of 4 inputs that are in a table and get the sum of the numbers on the input with a for loop but i keep getting 0 (the sum that i have defined)
Debugged everything and I am pretty sure the problem is in the "var x"- it just won't get any information from the inputs.
$(function () {
$("#inventoryForm").submit(function (event) {
var table = $("table")
var error = false;
event.preventDefault();
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
error = true; //Indicate there was an error
$("#inventoryError").slideDown().text("Positive numbers only");
return false; //This stops the iteration
}
});
//Stop processing if there was an error
if (error) return;
if (!error) {
$("#inventoryError").hide();
}
$("#inventorySubmit").hide();
$("#inventoryChange").show();
$("#withdraw").show();
$(".inventoryInput").attr('disabled','disabled');
var sum = 0;
var money = table.find("td:nth-child(2)");
for (var i = 0; i<money.length; i++) {
var x = money.eq(i).val();
sum += x;
$("#totalMoney").text(sum);
}
console.log(money);
});
$("#inventoryChange").click(function () {
$("#inventorySubmit").show();
$("#inventoryChange").hide();
$("#withdraw").hide();
$(".inventoryInput").removeAttr('disabled');
});
});
.hidden {
display: none;
}
.error {
display: none;
color: red;
border: dotted 3px yellow;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>ATM</title>
<body>
<header>
<h1>Litman - Steklov ATMs</h1>
</header>
<section id="inventory">
<form id="inventoryForm">
<table>
<thead>
<tr>
<th>Bill</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>
<input id="inventoryInput" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>50</td>
<td>
<input id="inventoryInput2" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>100</td>
<td>
<input id="inventoryInput3" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>200</td>
<td>
<input id="inventoryInput4" class="inventoryInput" type="number">
</td>
</tr>
</tbody>
</table>
<p id="inventoryError" class="error hidden">Validation errors will be here</p>
<p>Total Money: <span id="totalMoney"></span>
</p>
<button id="inventorySubmit" type="submit">Finish</button>
<button id="inventoryChange" type="button" class="hidden">Change</button>
</form>
</section>
<section id="withdraw" class="hidden">
<form>
<div>Withdraw:
<input type="number">
</div>
<p class="error hidden">Validation errors will be here</p>
<button type="submit">Process</button>
</form>
</section>
<section id="result" class="hidden">
<div>You Got:</div>
<button type="button">Finish</button>
</section>
</body>
</html>
The problem is indeed with
var x = money.eq(i).val();
money is an array of tds. So money.eq(i) is a td. What you want to get to is the actual input. So the solution is
var x = money.eq(i).find('input').val();
To elaborate on your further commend. If you fill in all 4 inputs using
var x = parseInt(money.eq(i).find('input').val());
it will sum them as expected. It will throw NaN when one of the inputs is empty because parseInt('') returns NaN, so you should check if the input actually has a value or not..
var input = money.eq(i).find('input').val();
var x = input ? parseInt(input) : 0
To further explain my code.
var input = money.eq(i).find('input').val();
This gets the value of the actual input, whatever that value may be.
var x = input ? parseInt(input) : 0
This checks whether the value of the input is empty or not. If it is empty then x=0 otherwise x=parseInt(input). So if the input is not empty, the value if being parsed to an int and assigned to x.
sum += x
x is being added to the final sum.