Subtracting the result of two sums - javascript

I'm trying to subtract two totals.
I have one table for incomes, were the final row is the "total incomes" and another table for expenses, with a final row for the "total expenses"
I need to add another function that calculates the total income minus the total expenses. I also need to show a negative amount in case the expenses are greater than the incomes.
My problem is, I don't quite understand how to use the value that its stored on my previous function so I can reuse it on the new one. I'm fairly new to javascript/jquery so I'm having troubles understanding the documentation.
Any guidance on this will be very much appreciated
Here is the js
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txtA").each(function () {
$(this).keyup(function () {
calculateSumA();
calculateSubstraction();
});
});
});
function calculateSumA() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txtA").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sumA").html(sum.toFixed(2));
}
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function () {
$(this).keyup(function () {
calculateSum();
calculateSubstraction();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
function calculateSubstraction() {
var subs = calculateSum() - calculateSumA();
$("#subs").html(subs.toFixed(2));
}
here is the html
<body>
<table width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td> </td>
<td align="right">total income:</td>
<td align="center"><span id="sumA">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td> </td>
<td align="right">total expenses:</td>
<td align="center"><span id="sum">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="su">0</span>
</td>
</tr>
</table>
http://jsfiddle.net/gnzLwzuy/5/
I know it could be optimized, as I'm repeating the code too much, but If I change it too much It stops working.
(I have too much to learn...)

Just to complement Guruprasad answer, and to responde directly to how can a function access a value calculated by another function.
The easy way:
1 - declare global variables and use them inside your functions.
var foo;
function calculateSumA() {
....
foo = some value;
}
function OtherFunc() {
....
var localVar = foo;
}
2 - make the functions return a value and store it somewhere other functions can access (e.g a global variable);
Not so simple way:
You can use closures to create the illusion of private members.
I wrote an article on JS Closures. I believe it will help you understand the concept quite well, if you are curious about it: https://usonsci.wordpress.com/2014/10/04/closure-with-javascript/

However you are calling calculateSubstraction on keyup of each textbox just take the value from total of each section and subtract it accordingly as below:
function calculateSubstraction() {
var subs=parseFloat($("#sumA").text()) - parseFloat($("#sum").text())
$("#su").html(subs);
}
DEMO
Update
Here is the more optimized version of your code. I prefer blur event than keyup since its more reliable to calculate and reduces the firing of event on every keypress
$(document).ready(function () {
var income = 0;//variable to hold income
var expense= 0; //variable to hold expense
$(".txtA,.txt").blur(function () { //attach event to multiple elements
$(this).each(function () {//loop through each of them
if (!isNaN(this.value) && this.value.length != 0) {
if($(this).hasClass('txt')) //if it is expense
expense += parseFloat(this.value); //add it to expense
else
income+=parseFloat(this.value); //add it to income
}
});
if($(this).hasClass('txt'))
$("#sum").html(expense.toFixed(2)); //display based on income or expense
else
$("#sumA").html(income.toFixed(2));
calculateSubstraction();//this remains same
});
});
Updated DEMO

DEMO
You need to return a value from the add functions so add
return sum.toFixed(2);
return sum.toFixed(2);
from the two function and did the subtraction from the subtract function
var data = calculateSum();
var dataa = calculateSumA();
var subs = dataa-data;
$("#su").html(subs.toFixed(2));

Just Replace your calculateSubstraction() function with this :
function calculateSubstraction() {
var Income = parseFloat($('#sumA').html());
var Expense = parseFloat($('#sum').html());
var subs = Income - Expense;
$("#su").html(subs.toFixed(2));
}

Using jQuery, you can have a simple calculation like
jQuery(function() {
var sum = {
income: 0,
deduction: 0
};
$('input.entry').keyup(function() {
var $table = $(this).closest('table'),
total = 0;
$table.find('input.entry').each(function() {
total += +this.value || 0;
});
$table.find('span.total').html(total)
sum[$table.data('type')] = total;
$('#su').html(sum.income - sum.deduction);
})
})
body {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border-color: white;
background-color: powderblue;
}
input.entry {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="300px" border="1" class="entry" data-type="income">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA entry" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td> </td>
<td align="right">total income:</td>
<td align="center"><span class="total">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1" class="entry" data-type="deduction">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt entry" type="text" name="txt" />
</td>
</tr>
<tr>
<td> </td>
<td align="right">total expenses:</td>
<td align="center"><span class="total">0</span></td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="su">0</span>
</td>
</tr>
</table>

I've made a pure Javascript version of your code, and added two new functionalities:
A button to dynamically add new rows to the income and expense tables.
And remove the ability of user adding anything other than numbers to the textfields.
The full commented code is below:
/* when all elements of the page are available */
document.addEventListener('DOMContentLoaded', function() {
/* get the tables income and expense, and the 'total' fields */
var income = document.getElementById('income'),
expense = document.getElementById('expense'),
totalIncome = document.getElementById('totalIncome'),
totalExpense = document.getElementById('totalExpense'),
total = document.getElementById('total');
/* create the calculate function */
function calculate(e) {
/* get all the textfields of each table */
var incomes = [].slice.call(income.querySelectorAll('input')),
expenses = [].slice.call(expense.querySelectorAll('input'));
/* calculate the sum of the fields by using
- map to convert the values to numbers
- and reduce to sum those values */
var sumIncome = incomes.map(function(el) {
/* don't allow users to input other values than numbers */
el.value = el.value.replace(/[^0-9\.]/g, '');
return Number(el.value);
}).reduce(function(a, b) {
return a + b;
});
var sumExpense = expenses.map(function(el) {
/* don't allow users to input other values than numbers */
el.value = el.value.replace(/[^0-9\.]/g, '');
return Number(el.value);
}).reduce(function(a, b) {
return a + b;
});
/* change the totalIncome and totalExpense labels */
totalIncome.textContent = sumIncome;
totalExpense.textContent = sumExpense;
/* change the total remaining label */
total.textContent = sumIncome - sumExpense;
}
/* add the event handlers to the oninput event to both tables
they will call the calculate function above when they happen */
income.addEventListener('input', calculate);
expense.addEventListener('input', calculate);
/* this is a bonus, I've added 'new' buttons to dynamically add more rows */
document.addEventListener('click', function(e) {
var el = e.target;
if (el.className === 'new') {
var table = el.parentNode.parentNode.parentNode,
tr = document.createElement('tr');
tr.innerHTML = '<td>' + [].slice.call(table.querySelectorAll('tr')).length + '</td>\
<td>income</td>\
<td>\
<input class="txtA" type="text" />\
</td>';
table.insertBefore(tr, el.parentNode.parentNode);
}
});
});
body {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border-color: white;
background-color: powderblue;
}
.txt,
.txtA {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}
<table id='income' width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>income</td>
<td>
<input class="txtA" type="text" name="txt" />
</td>
</tr>
<tr class="income">
<td>
<button class="new">new</button>
</td>
<td align="right">total income:</td>
<td align="center"><span id="totalIncome">0</span>
</td>
</tr>
</table>
<br/>
<table id='expense' width="300px" border="1">
<tr>
<td width="40px">1</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>expense</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>
<button class="new">new</button>
</td>
<td align="right">total expenses:</td>
<td align="center"><span id="totalExpense">0</span>
</td>
</tr>
</table>
<br/>
<table width="300px" border="1">
<tr>
<td style="width:40px"></td>
<td style="width:62px">Remaining:</td>
<td align="center"><span id="total">0</span>
</td>
</tr>
</table>

Related

How to Pass HTML Input values (batch) to Google Spreadsheet using only JavaScript?

I am using Google Scripts App, and I need to send the value of a batch of HTML Inputs to a Google Spreadsheet, on specific cells (row and column). However, the code I used, takes forever, and when it finish, not all inputs are passed to the Spreadsheet. Do to company restrictions (policies on software), I can only use pure JavaScript. This HTML page, is just a part of an App whit others pages, so using Google Forms, can’t be an option.
Is there a better way to send the inputs values to Google Spreadsheet faster and without skipping inputs?
I know that using too much “google.script.run”, slows down the process heavily, but can’t figure out another way. I am new at this, so don’t expect I know too much, just the barely basics.
Because of STACKOVERFLOW limitation, I limited the code to only three MODULES and 20 inputs per module (but there are four MODULES, with 30 inputs per module, as you can see it in the picture).
What alternative would you all recommend?
I am sharing the Code.gs and HTML scripts.
Thanks.
code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile("HTML_start_page")
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
return HtmlService.createHtmlOutputFromFile('HTML_start_page');
}
var ss = SpreadsheetApp.openByUrl("YOUR_GOOGLE_SPREADSHEET_URL_HERE");
var sheet_Balance = ss.getSheetByName("Page_1");
function getValuesFromForm_Balance_001A(id2000_01AA){
sheet_Balance.getRange(267,6).setValue(id2000_01AA);
}
function getValuesFromForm_Balance_002A(id2000_02AA){
sheet_Balance.getRange(268,6).setValue(id2000_02AA);
}
function getValuesFromForm_Balance_003A(id2000_03AA){
sheet_Balance.getRange(269,6).setValue(id2000_03AA);
}
function getValuesFromForm_Balance_004A(id2000_04AA){
sheet_Balance.getRange(270,6).setValue(id2000_04AA);
}
function getValuesFromForm_Balance_005A(id2000_05AA){
sheet_Balance.getRange(271,6).setValue(id2000_05AA);
}
function getValuesFromForm_Balance_006A(id1000_01AA){
sheet_Balance.getRange(272,6).setValue(id1000_01AA);
}
function getValuesFromForm_Balance_007A(id1000_02AA){
sheet_Balance.getRange(273,6).setValue(id1000_02AA);
}
function getValuesFromForm_Balance_008A(id1000_03AA){
sheet_Balance.getRange(274,6).setValue(id1000_03AA);
}
function getValuesFromForm_Balance_009A(id1000_04AA){
sheet_Balance.getRange(275,6).setValue(id1000_04AA);
}
function getValuesFromForm_Balance_010A(id1000_05AA){
sheet_Balance.getRange(276,6).setValue(id1000_05AA);
}
function getValuesFromForm_Balance_011A(id500_01AA){
sheet_Balance.getRange(277,6).setValue(id500_01AA);
}
function getValuesFromForm_Balance_012A(id500_02AA){
sheet_Balance.getRange(278,6).setValue(id500_02AA);
}
function getValuesFromForm_Balance_013A(id500_03AA){
sheet_Balance.getRange(279,6).setValue(id500_03AA);
}
function getValuesFromForm_Balance_014A(id500_04AA){
sheet_Balance.getRange(280,6).setValue(id500_04AA);
}
function getValuesFromForm_Balance_015A(id500_05AA){
sheet_Balance.getRange(281,6).setValue(id500_05AA);
}
function getValuesFromForm_Balance_016A(id200_01AA){
sheet_Balance.getRange(282,6).setValue(id200_01AA);
}
function getValuesFromForm_Balance_017A(id200_02AA){
sheet_Balance.getRange(283,6).setValue(id200_02AA);
}
function getValuesFromForm_Balance_018A(id200_03AA){
sheet_Balance.getRange(284,6).setValue(id200_03AA);
}
function getValuesFromForm_Balance_019A(id200_04AA){
sheet_Balance.getRange(285,6).setValue(id200_04AA);
}
function getValuesFromForm_Balance_020A(id200_05AA){
sheet_Balance.getRange(286,6).setValue(id200_05AA);
}
function getValuesFromForm_Balance_001B(id2000_01BB){
sheet_Balance.getRange(267,7).setValue(id2000_01BB);
}
function getValuesFromForm_Balance_002B(id2000_02BB){
sheet_Balance.getRange(268,7).setValue(id2000_02BB);
}
function getValuesFromForm_Balance_003B(id2000_03BB){
sheet_Balance.getRange(269,7).setValue(id2000_03BB);
}
function getValuesFromForm_Balance_004B(id2000_04BB){
sheet_Balance.getRange(270,7).setValue(id2000_04BB);
}
function getValuesFromForm_Balance_005B(id2000_05BB){
sheet_Balance.getRange(271,7).setValue(id2000_05BB);
}
function getValuesFromForm_Balance_006B(id1000_01BB){
sheet_Balance.getRange(272,7).setValue(id1000_01BB);
}
function getValuesFromForm_Balance_007B(id1000_02BB){
sheet_Balance.getRange(273,7).setValue(id1000_02BB);
}
function getValuesFromForm_Balance_008B(id1000_03BB){
sheet_Balance.getRange(274,7).setValue(id1000_03BB);
}
function getValuesFromForm_Balance_009B(id1000_04BB){
sheet_Balance.getRange(275,7).setValue(id1000_04BB);
}
function getValuesFromForm_Balance_010B(id1000_05BB){
sheet_Balance.getRange(276,7).setValue(id1000_05BB);
}
function getValuesFromForm_Balance_011B(id500_01BB){
sheet_Balance.getRange(277,7).setValue(id500_01BB);
}
function getValuesFromForm_Balance_012B(id500_02BB){
sheet_Balance.getRange(278,7).setValue(id500_02BB);
}
function getValuesFromForm_Balance_013B(id500_03BB){
sheet_Balance.getRange(279,7).setValue(id500_03BB);
}
function getValuesFromForm_Balance_014B(id500_04BB){
sheet_Balance.getRange(280,7).setValue(id500_04BB);
}
function getValuesFromForm_Balance_015B(id500_05BB){
sheet_Balance.getRange(281,7).setValue(id500_05BB);
}
function getValuesFromForm_Balance_016B(id200_01BB){
sheet_Balance.getRange(282,7).setValue(id200_01BB);
}
function getValuesFromForm_Balance_017B(id200_02BB){
sheet_Balance.getRange(283,7).setValue(id200_02BB);
}
function getValuesFromForm_Balance_018B(id200_03BB){
sheet_Balance.getRange(284,7).setValue(id200_03BB);
}
function getValuesFromForm_Balance_019B(id200_04BB){
sheet_Balance.getRange(285,7).setValue(id200_04BB);
}
function getValuesFromForm_Balance_020B(id200_05BB){
sheet_Balance.getRange(286,7).setValue(id200_05BB);
}
function getValuesFromForm_Balance_001C(id2000_01CC){
sheet_Balance.getRange(267,8).setValue(id2000_01CC);
}
function getValuesFromForm_Balance_002C(id2000_02CC){
sheet_Balance.getRange(268,8).setValue(id2000_02CC);
}
function getValuesFromForm_Balance_003C(id2000_03CC){
sheet_Balance.getRange(269,8).setValue(id2000_03CC);
}
function getValuesFromForm_Balance_004C(id2000_04CC){
sheet_Balance.getRange(270,8).setValue(id2000_04CC);
}
function getValuesFromForm_Balance_005C(id2000_05CC){
sheet_Balance.getRange(271,8).setValue(id2000_05CC);
}
function getValuesFromForm_Balance_006C(id1000_01CC){
sheet_Balance.getRange(272,8).setValue(id1000_01CC);
}
function getValuesFromForm_Balance_007C(id1000_02CC){
sheet_Balance.getRange(273,8).setValue(id1000_02CC);
}
function getValuesFromForm_Balance_008C(id1000_03CC){
sheet_Balance.getRange(274,8).setValue(id1000_03CC);
}
function getValuesFromForm_Balance_009C(id1000_04CC){
sheet_Balance.getRange(275,8).setValue(id1000_04CC);
}
function getValuesFromForm_Balance_010C(id1000_05CC){
sheet_Balance.getRange(276,8).setValue(id1000_05CC);
}
function getValuesFromForm_Balance_011C(id500_01CC){
sheet_Balance.getRange(277,8).setValue(id500_01CC);
}
function getValuesFromForm_Balance_012C(id500_02CC){
sheet_Balance.getRange(278,8).setValue(id500_02CC);
}
function getValuesFromForm_Balance_013C(id500_03CC){
sheet_Balance.getRange(279,8).setValue(id500_03CC);
}
function getValuesFromForm_Balance_014C(id500_04CC){
sheet_Balance.getRange(280,8).setValue(id500_04CC);
}
function getValuesFromForm_Balance_015C(id500_05CC){
sheet_Balance.getRange(281,8).setValue(id500_05CC);
}
function getValuesFromForm_Balance_016C(id200_01CC){
sheet_Balance.getRange(282,8).setValue(id200_01CC);
}
function getValuesFromForm_Balance_017C(id200_02CC){
sheet_Balance.getRange(283,8).setValue(id200_02CC);
}
function getValuesFromForm_Balance_018C(id200_03CC){
sheet_Balance.getRange(284,8).setValue(id200_03CC);
}
function getValuesFromForm_Balance_019C(id200_04CC){
sheet_Balance.getRange(285,8).setValue(id200_04CC);
}
function getValuesFromForm_Balance_020C(id200_05CC){
sheet_Balance.getRange(286,8).setValue(id200_05CC);
}
html
<!DOCTYPE html>
<html>
<body>
<!-- MODULE I ---->
<div>
<form style="border:0px solid #1f3f79; float:left; padding-left: 5px;">
<table>
<div>
<tr>
<tr>
<td>
<label>MODULE I</label>
<br>
<input type="text" value="0" id="id2000_01AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_02AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_03AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_04AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_05AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_01AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_02AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_03AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_04AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_05AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_01AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_02AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_03AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_04AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_05AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_01AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_02AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_03AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_04AA">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_05AA">
</td>
</tr>
</div>
</table>
</form>
</div>
<!-- MODULE II ---->
<div>
<form style="border:0px solid #1f3f79; float:left; padding-left: 5px;">
<table>
<div>
<tr>
<tr>
<td>
<label>MODULE II</label>
<br>
<input type="text" value="0" id="id2000_01BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_02BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_03BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_04BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_05BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_01BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_02BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_03BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_04BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_05BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_01BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_02BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_03BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_04BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_05BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_01BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_02BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_03BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_04BB">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_05BB">
</td>
</tr>
</div>
</table>
</form>
</div>
<!-- MODULE III ---->
<div>
<form style="border:0px solid #1f3f79; float:left; padding-left: 5px;">
<table>
<div>
<tr>
<tr>
<td>
<label>MODULE III</label>
<br>
<input type="text" value="0" id="id2000_01CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_02CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_03CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_04CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id2000_05CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_01CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_02CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_03CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_04CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id1000_05CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_01CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_02CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_03CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_04CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id500_05CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_01CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_02CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_03CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_04CC">
</td>
</tr>
<tr>
<td>
<input type="text" value="0" id="id200_05CC">
</td>
</tr>
</div>
</table>
</form>
</div>
<div>
<input type='button' id="botonREGISTRAR" value='REGISTER' onclick="get_New_Balances()">
</div>
<script>
function get_New_Balances() {
google.script.run.getValuesFromForm_Balance_001A(document.getElementById("id2000_01AA").value);
google.script.run.getValuesFromForm_Balance_002A(document.getElementById("id2000_02AA").value);
google.script.run.getValuesFromForm_Balance_003A(document.getElementById("id2000_03AA").value);
google.script.run.getValuesFromForm_Balance_004A(document.getElementById("id2000_04AA").value);
google.script.run.getValuesFromForm_Balance_005A(document.getElementById("id2000_05AA").value);
google.script.run.getValuesFromForm_Balance_006A(document.getElementById("id1000_01AA").value);
google.script.run.getValuesFromForm_Balance_007A(document.getElementById("id1000_02AA").value);
google.script.run.getValuesFromForm_Balance_008A(document.getElementById("id1000_03AA").value);
google.script.run.getValuesFromForm_Balance_009A(document.getElementById("id1000_04AA").value);
google.script.run.getValuesFromForm_Balance_010A(document.getElementById("id1000_05AA").value);
google.script.run.getValuesFromForm_Balance_011A(document.getElementById("id500_01AA").value);
google.script.run.getValuesFromForm_Balance_012A(document.getElementById("id500_02AA").value);
google.script.run.getValuesFromForm_Balance_013A(document.getElementById("id500_03AA").value);
google.script.run.getValuesFromForm_Balance_014A(document.getElementById("id500_04AA").value);
google.script.run.getValuesFromForm_Balance_015A(document.getElementById("id500_05AA").value);
google.script.run.getValuesFromForm_Balance_016A(document.getElementById("id200_01AA").value);
google.script.run.getValuesFromForm_Balance_017A(document.getElementById("id200_02AA").value);
google.script.run.getValuesFromForm_Balance_018A(document.getElementById("id200_03AA").value);
google.script.run.getValuesFromForm_Balance_019A(document.getElementById("id200_04AA").value);
google.script.run.getValuesFromForm_Balance_020A(document.getElementById("id200_05AA").value);
google.script.run.getValuesFromForm_Balance_001B(document.getElementById("id2000_01BB").value);
google.script.run.getValuesFromForm_Balance_002B(document.getElementById("id2000_02BB").value);
google.script.run.getValuesFromForm_Balance_003B(document.getElementById("id2000_03BB").value);
google.script.run.getValuesFromForm_Balance_004B(document.getElementById("id2000_04BB").value);
google.script.run.getValuesFromForm_Balance_005B(document.getElementById("id2000_05BB").value);
google.script.run.getValuesFromForm_Balance_006B(document.getElementById("id1000_01BB").value);
google.script.run.getValuesFromForm_Balance_007B(document.getElementById("id1000_02BB").value);
google.script.run.getValuesFromForm_Balance_008B(document.getElementById("id1000_03BB").value);
google.script.run.getValuesFromForm_Balance_009B(document.getElementById("id1000_04BB").value);
google.script.run.getValuesFromForm_Balance_010B(document.getElementById("id1000_05BB").value);
google.script.run.getValuesFromForm_Balance_011B(document.getElementById("id500_01BB").value);
google.script.run.getValuesFromForm_Balance_012B(document.getElementById("id500_02BB").value);
google.script.run.getValuesFromForm_Balance_013B(document.getElementById("id500_03BB").value);
google.script.run.getValuesFromForm_Balance_014B(document.getElementById("id500_04BB").value);
google.script.run.getValuesFromForm_Balance_015B(document.getElementById("id500_05BB").value);
google.script.run.getValuesFromForm_Balance_016B(document.getElementById("id200_01BB").value);
google.script.run.getValuesFromForm_Balance_017B(document.getElementById("id200_02BB").value);
google.script.run.getValuesFromForm_Balance_018B(document.getElementById("id200_03BB").value);
google.script.run.getValuesFromForm_Balance_019B(document.getElementById("id200_04BB").value);
google.script.run.getValuesFromForm_Balance_020B(document.getElementById("id200_05BB").value);
google.script.run.getValuesFromForm_Balance_001C(document.getElementById("id2000_01CC").value);
google.script.run.getValuesFromForm_Balance_002C(document.getElementById("id2000_02CC").value);
google.script.run.getValuesFromForm_Balance_003C(document.getElementById("id2000_03CC").value);
google.script.run.getValuesFromForm_Balance_004C(document.getElementById("id2000_04CC").value);
google.script.run.getValuesFromForm_Balance_005C(document.getElementById("id2000_05CC").value);
google.script.run.getValuesFromForm_Balance_006C(document.getElementById("id1000_01CC").value);
google.script.run.getValuesFromForm_Balance_007C(document.getElementById("id1000_02CC").value);
google.script.run.getValuesFromForm_Balance_008C(document.getElementById("id1000_03CC").value);
google.script.run.getValuesFromForm_Balance_009C(document.getElementById("id1000_04CC").value);
google.script.run.getValuesFromForm_Balance_010C(document.getElementById("id1000_05CC").value);
google.script.run.getValuesFromForm_Balance_011C(document.getElementById("id500_01CC").value);
google.script.run.getValuesFromForm_Balance_012C(document.getElementById("id500_02CC").value);
google.script.run.getValuesFromForm_Balance_013C(document.getElementById("id500_03CC").value);
google.script.run.getValuesFromForm_Balance_014C(document.getElementById("id500_04CC").value);
google.script.run.getValuesFromForm_Balance_015C(document.getElementById("id500_05CC").value);
google.script.run.getValuesFromForm_Balance_016C(document.getElementById("id200_01CC").value);
google.script.run.getValuesFromForm_Balance_017C(document.getElementById("id200_02CC").value);
google.script.run.getValuesFromForm_Balance_018C(document.getElementById("id200_03CC").value);
google.script.run.getValuesFromForm_Balance_019C(document.getElementById("id200_04CC").value);
google.script.run.getValuesFromForm_Balance_020C(document.getElementById("id200_05CC").value);
}
</script>
</body>
</html>
Here is the optimized and working code. Read the change logs below.
Code.gs:
function doGet() {
var template = HtmlService.createTemplateFromFile("HTML_start_page")
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getValuesFromForm(inputs){
var ss = SpreadsheetApp.openByUrl("spreadsheet url");
var sheet_Balance = ss.getSheetByName("Page_1");
// use setValues to write the 2D data by bulk
sheet_Balance.getRange(267, 7, inputs.length, inputs[0].length).setValues(inputs);
}
HTML_start_page.html:
<!DOCTYPE html>
<html>
<body>
<div>
<form style="border:0px solid #1f3f79; float:left; padding-left: 5px;">
<table id="table">
<tr>
<td><label>MODULE I</label></td>
<td><label>MODULE II</label></td>
<td><label>MODULE III</label></td>
<td><label>MODULE IV</label></td>
</tr>
</table>
</form>
</div>
<div>
<input type='button' id="botonREGISTRAR" value='REGISTER' onclick="get_New_Balances()">
</div>
<script>
window.onload = function () {
// automatically generate input rows
var table = document.getElementById("table");
var row, input, cell;
for (i = 0; i < 30; i++) {
row = table.insertRow();
for (j = 0; j < 4; j++) {
input = document.createElement('input')
input.type='text';
input.value='0';
cell = row.insertCell();
cell.appendChild(input);
}
}
};
function get_New_Balances() {
var tableRows = document.getElementById("table").rows;
var myrow, mytd;
var row = [], inputs = [];
for (i = 1; i < tableRows.length; i++) {
myrow = tableRows[i];
row = [];
for (j = 0; j < myrow.cells.length; j++) {
mytd = myrow.cells[j];
row.push(mytd.children[0].value);
}
inputs.push(row);
}
google.script.run.getValuesFromForm(inputs);
}
</script>
</body>
</html>
Change logs:
HTML table is now generated by a loop.
get_New_Balances now creates a 2D array from the table, and then passes it to the new function that writes 2D data directly to the sheet
getValuesFromForm is now using setValues to write the 2D data generated from the get_New_Balances
Input:
Output:
References:
Get the values of input field of each row of html table
Add and removing rows [with input field] in a table
About the same solution as #NaziA, without auto generation the HTML:
HTML:
...
<script>
function get_New_Balances() {
var nums1 = ['2000', '1000', '500', '200'];
var nums2 = ['01', '02', '03', '04', '05'];
var letters = ['AA', 'BB', 'CC'];
var values = [];
letters.forEach(letter => nums1.forEach(n1 => nums2.forEach(n2 => {
var id = 'id' + n1 + '_' + n2 + letter;
values.push(document.getElementById(id).value);
})));
var table = new Array(values.length / letters.length).fill('');
table = table.map((_, row) =>
letters.map((_, col) => values[row + table.length * col]));
google.script.run.main(table);
}
</script>
...
GS:
function doGet() {
var template = HtmlService.createTemplateFromFile("HTML_start_page");
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function main(table) {
var ss = SpreadsheetApp.openByUrl("URL");
var sheet_Balance = ss.getSheetByName("Page_1");
sheet_Balance.getRange(267,6,table.length,table[0].length).setValues(table);
}

how to get the sum of all row value in jquery

I'm trying to achieve two additions in my code.
I am trying to get the sum of the row values in the last column of the row
I am trying to get the sum of all the final columns in another div
I've achieved the first, my code gives me the correct value of each row. However the second sum is not populating the addition. It's giving me the same value of each row, but I want the value of all rows.
$('.bonus-sum').keyup(function() {
var sum = 0;
var salary = parseFloat($(this).closest('tr').find('.wagein').text());
var bonus = parseFloat($(this).closest('tr').find('.bonus-sum').val()) || 0;
$(this).closest('tr').find('.bonus-in:checked').each(function() {
sum = salary + bonus;
});
$(this).closest('tr').find('.netpay').text(sum.toFixed(2));
var netpay = 0;
netpay += sum;
$('#total').text('₹ ' + netpay.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class="text-center"><input type="checkbox" checked="checked" class="checkAll" name="checkAll" /></th>
<th>#</th>
<th>Beneficiary Name</th>
<th class="text-right box">Bonus ₹</th>
<th class="text-right">Salary ₹</th>
<th class="text-right">Net pay ₹</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>1</td>
<td>Chellammal Kochimoni</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>2</td>
<td>Christal Prema G.</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>3</td>
<td>Kamalesan T.</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>4</td>
<td>Palammal A.</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" id="bene_id" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>4</td>
<td>Thangapazham</td>
<td><input type="text" id="bonus_temp" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
</tbody>
</table>
</div>
<div>Total Net Pay <span id="total">₹ 0.00</span></div>
To fix this you need to create a loop which iterates through all the .netpay elements, not just the one which was updated, and generates the total value.
In addition, you need to perform the same action when the checkbox is changed. The logic itself can also be made more succinct and DRY, like this:
$('.bonus-sum').on('input', updateRowTotal);
$('.bonus-in').on('change', updateRowTotal).trigger('change'); // trigger is to set values on load
function updateRowTotal() {
let $tr = $(this).closest('tr');
let salary = parseFloat($tr.find('.wagein').text()) || 0;
let bonus = parseFloat($tr.find('.bonus-sum').val()) || 0
let rowTotal = salary + ($tr.find('.bonus-in:checked').length ? bonus : 0);
$tr.find('.netpay').text(rowTotal.toFixed(2));
updateTotal();
}
function updateTotal() {
let total = 0;
$('.netpay').each((i, el) => total += parseFloat(el.textContent.trim() || 0));
$('#total').text('₹ ' + total.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class="text-center"><input type="checkbox" checked="checked" class="checkAll" name="checkAll" /></th>
<th>#</th>
<th>Beneficiary Name</th>
<th class="text-right box">Bonus ₹</th>
<th class="text-right">Salary ₹</th>
<th class="text-right">Net pay ₹</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>1</td>
<td>Chellammal Kochimoni</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>2</td>
<td>Christal Prema G.</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>3</td>
<td>Kamalesan T.</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>4</td>
<td>Palammal A.</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" class="bonus-in" name="bene_id[]" value="" />
</td>
<td>4</td>
<td>Thangapazham</td>
<td><input type="text" class="bonus-sum" name="bonus_temp[]" value="" /></td>
<td class="wagein">400</td>
<td class="netpay"></td>
</tr>
</tbody>
</table>
</div>
<div>Total Net Pay <span id="total">₹ 0.00</span></div>
Note the removal of all the duplicate id attributes in your HTML . They are invalid, and are not required anyway.
I have introduced new variable totalsum.
Replace the below function .your code will work as expected
<script>
var totalsum=0;
$('.bonus-sum').keyup(function() {
var sum = 0;
var salary = parseFloat($(this).closest('tr').find('.wagein').text());
var bonus = parseFloat($(this).closest('tr').find('.bonus-sum').val()) || 0;
$(this).closest('tr').find('.bonus-in:checked').each(function() {
sum = salary + bonus;
totalsum+=sum;
});
$(this).closest('tr').find('.netpay').text(sum.toFixed(2));
var netpay = 0;
netpay += totalsum;
$('#total').text('₹ ' + netpay.toFixed(2));
});
</script>

JavaScript input aggregation function not including default input values

I have a JavaScript function to aggregate the values of input fields, which I sourced from this answer to a similar question. My function appears to be working, however it only calculates the total value after one of the default values has been amended. How can I include the default values in the functions aggregation from the start? Here's a fiddle, and here's the code:
JavaScript:
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".qty1").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".qty1").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2)) * 0.2;}
html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
<tr>
<td width="40px">1</td>
<td>Butter</td>
<td><input class="txt" type="text" name="txt" value="65"/></td>
</tr>
<tr>
<td>2</td>
<td>Cheese</td>
<td><input class="txt" type="text" name="txt" value="32"/></td>
</tr>
<tr>
<td>3</td>
<td>Eggs</td>
<td><input class="txt" type="text" name="txt" value="47"/></td>
</tr>
<tr>
<td>4</td>
<td>Milk</td>
<td><input class="txt" type="text" name="txt" value="31"/></td>
</tr>
<tr>
<td>5</td>
<td>Bread</td>
<td><input class="txt" type="text" name="txt" value="69"/></td>
</tr>
<tr>
<td>6</td>
<td>Soap</td>
<td><input class="txt" type="text" name="txt" value="65"/></td>
</tr>
<tr id="summation">
<td> </td>
<td align="right">Sum :</td>
<td align="center"><span id="sum">0</span></td>
</tr>
Simply call calculateSum() inside $(document).ready and outside of the keyup event:
$(document).ready(function(){
calculateSum(); //call the function here
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
body {
font-family: sans-serif;
}
#summation {
font-size: 18px;
font-weight: bold;
color:#174C68;
}
.txt {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
<tr>
<td width="40px">1</td>
<td>Butter</td>
<td><input class="txt" type="text" name="txt" value="65"/></td>
</tr>
<tr>
<td>2</td>
<td>Cheese</td>
<td><input class="txt" type="text" name="txt" value="32"/></td>
</tr>
<tr>
<td>3</td>
<td>Eggs</td>
<td><input class="txt" type="text" name="txt" value="47"/></td>
</tr>
<tr>
<td>4</td>
<td>Milk</td>
<td><input class="txt" type="text" name="txt" value="31"/></td>
</tr>
<tr>
<td>5</td>
<td>Bread</td>
<td><input class="txt" type="text" name="txt" value="69"/></td>
</tr>
<tr>
<td>6</td>
<td>Soap</td>
<td><input class="txt" type="text" name="txt" value="65"/></td>
</tr>
<tr id="summation">
<td> </td>
<td align="right">Sum :</td>
<td align="center"><span id="sum">0</span></td>
</tr>
</table>

Do arithmetic calculations on Table elements

Hello and thank you in advance.
I have a table where some values prefilled (like 111.36) but when I try to do math with the numbers, or even display the number nothing happens.
Thank you for your assistance,
Marc (new at Javascript)
function calculate_it() {
window.alert("In function calculate_it");
var x = document.getElementByID("Numb01").value;
window.alert(x);
} //end function
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<TITLE>Javascript Table</TITLE>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<h3>A demonstration of calculators</h3>
<table id="t01">
<caption>Chek this out!</caption>
<tr>
<th>Date</th>
<th>Number 1</th>
<th>Number 2</th>
<th>Number 3</th>
<th>Number 4</th>
</tr>
<tr>
<td>
<input type="text" id="Date01" value="WED21DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb01" value=111.36 size="5" />
</td>
<td>
<input type="number" id="Numb02" value=222.36 size="5" />
</td>
<td>
<input type="number" id="Numb03" value=333.36 size="5" />
</td>
<td>
<input type="number" id="Numb04" value=444.36 size="5" />
</td>
</tr>
<tr>
<td>
<input type="text" id="Date02" value="WED22DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb05" value=555.36 size="5" />
</td>
<td>
<input type="number" id="Numb06" value=666.36 size="5" />
</td>
<td>
<input type="number" id="Numb07" value=777.36 size="5" />
</td>
<td>
<input type="number" id="Numb08" value=888.36 size="5" />
</td>
</tr>
<TR>
<td height="20" ColSpan="5"></td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Multiply:</td>
<td>
<input type="text" id="ActionMulti" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Add:</td>
<td>
<input type="text" id="ActionAdd" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Percentage:</td>
<td>
<input type="text" id="ActionPercentage" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>----------</td>
<td>--------</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Sum:</td>
<td>
<input type="text" id="Sum" value="" size="5" />
</td>
</TR>
</table>
<br>
<p>Click the button to calculate the data</p>
<button type="button" onclick="calculate_it()">calculate_it</button>
</body>
</html>
Well, I guess you already read all the comments saying the same: It's getElementById not getElementByID. Remember, JavaScript is case sensitive.
What you need to do for run your code successfuly are simple 2 things:
Store all input (number) values in an array.
Use a reduce function to get easy the result for the multiply, sum and percentage.
For example:
function calculate_it() {
var inputs = document.querySelectorAll('input[type="number"]');
var multiply = 0;
var add = 0;
var percentage = 0;
// get the values of each input, map then and return
// a new array with the parsed numbers
var numbers = [].map.call(inputs, function (i) {
return parseFloat(i.value);
});
multiply = numbers.reduce(function (n1, n2) {
return n1 * n2;
});
add = numbers.reduce(function (n1, n2) {
return n1 + n2;
});
percentage = numbers.reduce(function (n1, n2) {
return (n1 / n2) * 100;
});
document.getElementById('ActionMulti').value = multiply.toFixed(2);
document.getElementById('ActionAdd').value = add.toFixed(2);
document.getElementById('ActionPercentage').value = percentage.toFixed(2);
document.getElementById('Sum').value = (multiply + add + percentage).toFixed(2);
}
The toFixed of Number class returns an string representation of the number with the maximum numner of decimals passed as argument. It method round (classic round) the number if is necessary.
Full example
function calculate_it() {
var inputs = document.querySelectorAll('input[type="number"]');
var multiply = 0;
var add = 0;
var percentage = 0;
// get the values of each input, map then and return
// a new array with the parsed numbers
var numbers = [].map.call(inputs, function (i) {
return parseFloat(i.value);
});
multiply = numbers.reduce(function (n1, n2) {
return n1 * n2;
});
add = numbers.reduce(function (n1, n2) {
return n1 + n2;
});
percentage = numbers.reduce(function (n1, n2) {
return (n1 * n2) / 100;
});
document.getElementById('ActionMulti').value = multiply.toFixed(2);
document.getElementById('ActionAdd').value = add.toFixed(2);
document.getElementById('ActionPercentage').value = percentage.toFixed(8);
document.getElementById('Sum').value = (multiply + add + percentage).toFixed(2);
}
input {
width: 100%;
}
<h3>A demonstration of calculators</h3>
<table id="t01">
<caption>Chek this out!</caption>
<tr>
<th>Date</th>
<th>Number 1</th>
<th>Number 2</th>
<th>Number 3</th>
<th>Number 4</th>
</tr>
<tr>
<td>
<input type="text" id="Date01" value="WED21DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb01" value=11.36 size="5" />
</td>
<td>
<input type="number" id="Numb02" value=12.36 size="5" />
</td>
<td>
<input type="number" id="Numb03" value=7.36 size="5" />
</td>
<td>
<input type="number" id="Numb04" value=4.36 size="5" />
</td>
</tr>
<tr>
<td>
<input type="text" id="Date02" value="WED22DEC16" size="10" />
</td>
<td>
<input type="number" id="Numb05" value=8.36 size="5" />
</td>
<td>
<input type="number" id="Numb06" value=6.36 size="5" />
</td>
<td>
<input type="number" id="Numb07" value=10.36 size="5" />
</td>
<td>
<input type="number" id="Numb08" value=8.36 size="5" />
</td>
</tr>
<TR>
<td height="20" ColSpan="5"></td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Multiply:</td>
<td>
<input type="text" id="ActionMulti" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Add:</td>
<td>
<input type="text" id="ActionAdd" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Percentage:</td>
<td>
<input type="text" id="ActionPercentage" value="" size="5" />
</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>----------</td>
<td>--------</td>
</TR>
<TR>
<td height="20" ColSpan="2"></td>
<td ColSpan="2" class='alnright'>Sum:</td>
<td>
<input type="text" id="Sum" value="" size="5" />
</td>
</TR>
</table>
<br>
<p>Click the button to calculate the data</p>
<button type="button" onclick="calculate_it()">calculate_it</button>

How to sum Jquery Outputs

I created couple of rows and multiplied some data to get totals:
But I am not sure how to sum all the totals and print it in "Cash in Hand" row.
Following are my codes:
<script type="text/javascript">
$(document).ready(function() {
$('.row1').keyup(function(ev){
var row1c = $(this).val() * 1000;
$('.row1c').html((row1c).toFixed(2));
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.row2').keyup(function(ev){
var row2c = $(this).val() * 500;
$('.row2c').html((row2c).toFixed(2));
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.row3').keyup(function(ev){
var row3c = $(this).val() * 100;
$('.row3c').html((row3c).toFixed(2));
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.row4').keyup(function(ev){
var row4c = $(this).val() * 50;
$('.row4c').html((row4c).toFixed(2));
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.row5').keyup(function(ev){
var row5c = (row1c+row2c+row3c+row4c);
$('.row5c').html((row5c).toFixed(2));
});
});
</script>
<table border="2" cellpadding="5" cellspacing="2" align="center">
<h3 align="center">Cash Position as on...... </h3>
<tr>
<th>Note</th>
<th>Quantity</th>
<th>Total</th>
</tr>
<tr>
<td>1000 Tk Note</td>
<td><input type="text" name="pages" class="row1" /></td>
<td><span class="row1c">0.00</span></td>
</tr>
<tr>
<td>500 Tk Note</td>
<td><input type="text" name="pages" class="row2" /></td>
<td><span class="row2c">0.00</span></td>
</tr>
<tr>
<td>100 Tk Note</td>
<td><input type="text" name="pages" class="row3" /></td>
<td><span class="row3c">0.00</span></td>
</tr>
<tr>
<td>50 Tk Note</td>
<td><input type="text" name="pages" class="row4" /></td>
<td><span class="row4c">0.00</span></td>
</tr>
<tr>
<td colspan ="2">Cash In Hand (Sum of All Totals)</td>
<td><span class="row5c">0.00</span></td>
</tr>
</table>
All codes together here:
https://jsfiddle.net/rashelmiah/fb9opo36/1/
Could you please me find a way to sum all the totals?
Thanks in advance.
You need add the following code.
$('input[type=text]').keyup(function(){
var total = 0;
$('input[type=text]').each(function(){
total += Number($(this).parent().next().find('span').text());
})
$('.row5c').text(total);
})
Note: Your code had a lot of <script> tags which was unnecessary. And a lot of ready() function, which was unnecessary too. You can wrap the whole code inside one <script> tag and one ready() function.
Demo:
$(document).ready(function() {
$('.row1').keyup(function(ev){
var row1c = $(this).val() * 1000;
$('.row1c').html((row1c).toFixed(2));
});
$('.row2').keyup(function(ev){
var row2c = $(this).val() * 500;
$('.row2c').html((row2c).toFixed(2));
});
$('.row3').keyup(function(ev){
var row3c = $(this).val() * 100;
$('.row3c').html((row3c).toFixed(2));
});
$('.row4').keyup(function(ev){
var row4c = $(this).val() * 50;
$('.row4c').html((row4c).toFixed(2));
});
$('.row5').keyup(function(ev){
var row5c = (row1c+row2c+row3c+row4c);
$('.row5c').html((row5c).toFixed(2));
});
$('input[type=text]').keyup(function(){
var total = 0;
$('input[type=text]').each(function(){
total += Number($(this).parent().next().find('span').text());
})
$('.row5c').text(total.toFixed(2));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="2" cellpadding="5" cellspacing="2" align="center">
<h3 align="center">Cash Position as on...... </h3>
<tr>
<th>Note</th>
<th>Quantity</th>
<th>Total</th>
</tr>
<tr>
<td>1000 Tk Note</td>
<td>
<input type="text" name="pages" class="row1" />
</td>
<td><span class="row1c">0.00</span>
</td>
</tr>
<tr>
<td>500 Tk Note</td>
<td>
<input type="text" name="pages" class="row2" />
</td>
<td><span class="row2c">0.00</span>
</td>
</tr>
<tr>
<td>100 Tk Note</td>
<td>
<input type="text" name="pages" class="row3" />
</td>
<td><span class="row3c">0.00</span>
</td>
</tr>
<tr>
<td>50 Tk Note</td>
<td>
<input type="text" name="pages" class="row4" />
</td>
<td><span class="row4c">0.00</span>
</td>
</tr>
<tr>
<td colspan="2">Cash In Hand (Sum of All Totals)</td>
<td><span class="row5c">0.00</span>
</td>
</tr>
</table>

Categories