JavaScript input aggregation function not including default input values - javascript

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>

Related

How to customize jAutoCalc plugin

I have a simple question regarding jAutoCalc, my question can be answered in two ways:
1> How to customize the jAutoCalc plugin so that we can make it able to be used for input array names instead of just names.
my code is here:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="http://rawgit.com/c17r/jAutoCalc/master/jAutoCalc.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function() {
function autoCalcSetup() {
$('form[name=cart]').jAutoCalc('destroy');
$('form[name=cart] tr[name=line_items]').jAutoCalc({
keyEventsFire: true,
decimalPlaces: 2,
emptyAsZero: true
});
$('form[name=cart]').jAutoCalc({
decimalPlaces: 2
});
}
autoCalcSetup();
$('button[name=remove]').click(function(e) {
e.preventDefault();
var form = $(this).parents('form')
$(this).parents('tr').remove();
autoCalcSetup();
});
$('button[name=add]').click(function(e) {
e.preventDefault();
var $table = $(this).parents('table');
var $top = $table.find('tr[name=line_items]').first();
var $new = $top.clone(true);
$new.jAutoCalc('destroy');
$new.insertBefore($top);
$new.find('input[type=text]').val('');
autoCalcSetup();
});
});
</script>
</head>
<body>
<form name="cart">
<table name="cart">
<tr>
<th></th>
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th> </th>
<th>Item Total</th>
</tr>
<tr name="line_items">
<td><button name="remove">Remove</button></td>
<td>Stuff</td>
<td><input type="text" name="qty" value="1"></td>
<td><input type="text" name="price" value="9.99"></td>
<td> </td>
<td><input type="text" name="item_total" value="" jAutoCalc="{qty} * {price}"></td>
</tr>
<tr name="line_items">
<td><button name="remove">Remove</button></td>
<td>More Stuff</td>
<td><input type="text" name="qty" value="2"></td>
<td><input type="text" name="price" value="12.50"></td>
<td> </td>
<td><input type="text" name="item_total" value="" jAutoCalc="{qty} * {price}"></td>
</tr>
<tr name="line_items">
<td><button name="remove">Remove</button></td>
<td>And More Stuff</td>
<td><input type="text" name="qty" value="3"></td>
<td><input type="text" name="price" value="99.99"></td>
<td> </td>
<td><input type="text" name="item_total" value="" jAutoCalc="{qty} * {price}"></td>
</tr>
<tr>
<td colspan="3"> </td>
<td>Subtotal</td>
<td> </td>
<td><input type="text" name="sub_total" value="" jAutoCalc="SUM({item_total})"></td>
</tr>
<tr>
<td colspan="3"> </td>
<td>
Tax:
<select name="tax">
<option value=".06">CT Tax</option>
<option selected value=".00">Tax Free</option>
</select>
</td>
<td> </td>
<td><input type="text" name="tax_total" value="" jAutoCalc="{sub_total} * {tax}"></td>
</tr>
<tr>
<td colspan="3"> </td>
<td>Total</td>
<td> </td>
<td><input type="text" name="grand_total" value="" jAutoCalc="{sub_total} + {tax_total}"></td>
</tr>
<tr>
<td colspan="99"><button name="add">Add Row</button></td>
</tr>
</table>
</form>
</body>
</html>
since the names are same for dynamically generated input's i want use input array. The problem is that if i do so then I'm unable to use the plugin features!
2> The question can be answered in second way by providing methods to use plugin while using input arrays
I know its an old post but maybe others may have same issue.
Try to open jautocalc.js find this function "getFieldSelector(field)" and edit this code.
return ':input[name="' + field + '"]';
to
return ':input[name="' + field + '[]"]';
I think the whole problem is with javascript
the javascript should be like
$(document).ready(function(){
$('.item_total').keyup(function(){
$('your result input name here).text($('.item_total').val() * 1.5);
});
});
this link will help you:
http://jsfiddle.net/7BDwP/
You will get idea from the above link what i am trying to say

Get total from multiple class onchange

Goodday, i'm trying to get total and grandtotal from textinput . First please check my script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>No</td>
<td>Item</td>
<td>Qty</td>
<td>est</td>
<td>tax</td>
<td>Total</td>
<td>GrandTotal</td>
</tr>
<tr>
<td>No</td>
<td>ITEM 1</td>
<td>2</td>
<td><input type="text" class="est"></td>
<td><input type="text" class="tax"></td>
<td><input type="text" readonly class="total"></td>
<td><input type="text" readonly class="grandtotal"></td>
</tr>
<tr>
<td>No</td>
<td>ITEM 1</td>
<td>2</td>
<td><input type="text" class="est"></td>
<td><input type="text" class="tax"></td>
<td><input type="text" readonly class="total"></td>
<td><input type="text" readonly class="grandtotal"></td>
</tr>
</table>
As you can i see, there is .total and .grandtotal. I want to get it with this
total = .est * .qty
grandtotal = .total * .tax
So, i want to onchange in two fields .est & .tax .
Maybe i can do this
$(document).on("change",".tax",function(){
//Code
});
and
$(document).on("change",".tax",function(){
//Code
});
But it will take time, so i'm trying to approach this way
$(document).on("change",".tax, .est",function(){
//I don't know to get value of .tax or .est only
});
How can i get the total and grandtotal ?
run and see result
$('tr').each(function() {
var qty = $($(this).children()[2]).text(),
$tax = $(this).find(".tax"),
$est = $(this).find(".est"),
$total = $(this).find(".total"),
$grandtotal = $(this).find(".grandtotal")
function onChange() {
var t = $est.val() * qty
var gt = $tax.val() * t
$total.val(t)
$grandtotal.val(gt)
}
$tax.change(onChange)
$est.change(onChange)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>No</td>
<td>Item</td>
<td>Qty</td>
<td>est</td>
<td>tax</td>
<td>Total</td>
<td>GrandTotal</td>
</tr>
<tr>
<td>No</td>
<td>ITEM 1</td>
<td>2</td>
<td><input type="text" class="est"></td>
<td><input type="text" class="tax"></td>
<td><input type="text" readonly class="total"></td>
<td><input type="text" readonly class="grandtotal"></td>
</tr>
<tr>
<td>No</td>
<td>ITEM 1</td>
<td>2</td>
<td><input type="text" class="est"></td>
<td><input type="text" class="tax"></td>
<td><input type="text" readonly class="total"></td>
<td><input type="text" readonly class="grandtotal"></td>
</tr>
</table>
I hope this help
$(function() {
var resultTax = 0, resultEst = 0, total = 0;
$(".tax").change( function() {
$(".tax").each(function() {
resultTax += parseFloat($(this).val())
});
$('.resultTax').text(resultTax);
$('.total').text($('.resultEst').text() + $('.resultTax').text());
});
$(".est").change( function() {
$(".est").each(function() {
resultEst += parseFloat($(this).val())
});
$('.resultEst').text(resultEst);
$('.total').text(parseFloat($('.resultEst').text()) + parseFloat($('.resultTax').text()));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Tax <input type="text" class="tax" value="1">
Tax <input type="text" class="tax" value="2"><br>
Est <input type="text" class="est" value="3">
Est <input type="text" class="est" value="4"><br><br>
resultTax : <span class="resultTax"></span><br>
resultEst : <span class="resultEst"></span><br>
Total Tax + Est : <span class="total"></span>

Sum total of all text box value in a row using jquery

I want to sum all the text box value in a html table row using jQuery.
here is the table:
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
</table>
Here is the jQuery function to add the value of all text box of class expenses and display the result in a text box of id expenses_sum.
$(document).ready(function() {
$(".expenses").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$(".expenses").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#expenses_sum").val(sum.toFixed(2));
}
how to use this function for each row.
Firstly you have repeated the same id when they should be unique which means your HTML is invalid. You should use a common class instead.
To make this work you need to restrict the .expenses selector to only find the elements within the same row as the input which was changed. To do that you can use closest() to get the nearest parent tr, then find() to get all the inputs.
Also note there are several logic improvements you can make here:
remove the each() loop to add the event handler
providing the reference of calculateSum to the event handler so you can use the this keyword to traverse the DOM
provide a default value of 0 to the value to simplify the sum logic
hook to the change event as well as keyup for when users paste data in to the field. Try this:
$(document).ready(function() {
$(".expenses").on('keyup change', calculateSum);
});
function calculateSum() {
var $input = $(this);
var $row = $input.closest('tr');
var sum = 0;
$row.find(".expenses").each(function() {
sum += parseFloat(this.value) || 0;
});
$row.find(".expenses_sum").val(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
</table>
you can use like this
$(document).on('keyup change','input.expenses',function(){
$expenses = $(this).parents('tr').find('.expenses');
$expenseTotal = $(this).parents('tr').find('#expenses_sum');
$expenseTotal.val('0');
$.each($expenses,function(index,object){
if($(object).val()!='')
{
$expenseTotal.val(parseInt($expenseTotal.val())+parseInt($(object).val()));
}
});
});
see demo at - https://jsfiddle.net/Vesharj/zLg3pyq4/
Here is the right way to do this.
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
</table>
And js :
$(document).ready(function(){
$(".expenses").each(function() {
$(this).keyup(function(){
sum($(this).parents("tr"));
});
});
});
function sum(parent){
var sum = 0;
$(parent).find(".expenses").each(function(){
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$(parent).find(".expenses_sum").val(sum.toFixed(2));
}
Hope, it helps

Subtracting the result of two sums

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>

Computing the sum of a variable number of html table columns using Javascript

I have a table with a lot of columns, and each column consists of a text field with a numeric value that can be changed. The last column of the table must hold the sum of all columns. Now here's my question: how can I make the sum change in realtime using javascript? For example if a column value is modified, the sum must be changed in order to fit the new values.
Below is my table:
<table id="sum_table">
<tr>
<td>Column 1</td>
<td><input type="text" name="val1" value="" /></td>
</tr>
<tr>
<td>Column 2</td>
<td><input type="text" name="val2" value="" /></td>
</tr>
<tr>
<td>Column 3</td>
<td><input type="text" name="val3" value="" /></td>
</tr>
[...]
<tr>
<td>Total</td>
<td><input type="text" name="total" value="" /></td>
</tr>
</table>
Thank you.
<html>
<head>
<script type="text/javascript">
function calc()
{
var sum = parseFloat(document.getElementById('val1').value + document.getElementById('val2').value + document.getElementById('val3').value + [...]);
document.getElementById('total').value = sum;
}
</script>
</head>
<body>
<table id="sum_table">
<tr>
<td>Column 1</td>
<td><input type="text" id="val1" value="" OnTextChanged="javascript:calc()"/></td>
</tr>
<tr>
<td>Column 2</td>
<td><input type="text" id="val2" value="" OnTextChanged="javascript:calc()/></td>
</tr>
<tr>
<td>Column 3</td>
<td><input type="text" id="val3" value="" OnTextChanged="javascript:calc()/></td>
</tr>
[...]
<tr>
<td>Total</td>
<td><input type="text" id="total" value="" /></td>
</tr>
</table>
</body>
</html>
That should to the trick.
Edit:
After discussion in the comments, this is the final version: http://jsfiddle.net/gXdwb/3/
$('#sum_table tr:not(.totalColumn) input:text').bind('keyup change', function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalColumn) .sum'+thisNumber).each(function() {
total += +$(this).val();
});
$table.find('.totalColumn td:nth-child('+thisNumber+') input').val(total);
});
<table id="sum_table" width="600" border="0">
<tr>
<td>Sum 1</td>
<td>Sum 2</td>
<td>Sum 3</td>
</tr>
<tr>
<td><input type="text" name="textfield" id="textfield" class="sum1" /></td>
<td><input type="text" name="textfield2" id="textfield2" class="sum2" /></td>
<td><input type="text" name="textfield3" id="textfield3" class="sum3"/></td>
</tr>
<tr>
<td><input type="text" name="textfield4" id="textfield4" class="sum1" /></td>
<td><input type="text" name="textfield5" id="textfield5" class="sum2" /></td>
<td><input type="text" name="textfield6" id="textfield6" class="sum3" /></td>
</tr>
<tr>
<td><input type="text" name="textfield7" id="textfield7" class="sum1" /></td>
<td><input type="text" name="textfield8" id="textfield8" class="sum2"/></td>
<td><input type="text" name="textfield9" id="textfield9" class="sum3"/></td>
</tr>
<tr>
<td>Total</td>
<td>Total</td>
<td>Total</td>
</tr>
<tr class="totalColumn">
<td><input type="text" name="textfield10" id="textfield10" /></td>
<td><input type="text" name="textfield11" id="textfield11" /></td>
<td><input type="text" name="textfield12" id="textfield12" /></td>
</tr>
<tr>
<td>bla</td>
<td>bla</td>
<td>bla</td>
</tr>
</table>
As usual, I'm not sure if this is optimal, but it seems to work:
See: http://jsfiddle.net/gXdwb/
$('#sum_table tr:not(:last-child)').bind('keyup change', function() {
var $table = $(this).closest('table');
var total = 0;
$table.find('tr:not(:last-child) input:text').each(function() {
total += +$(this).val();
});
$table.find('input[name="total"]').val(total);
});

Categories