jQuery: calculate final total based on qty/price - javascript

I am trying to calculate unit total and based on that final total using jQuery, I am able to update unit total every time qty or price is updated, but not able to update final total.
Here is the code:
<table id="tblUpdate" class="dataTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Unit Total</th>
</tr>
</thead>
<tbody>
<cfset TotalPrice = 0>
<cfloop query="qItems">
<cfset vLineID = qItems.LineID>
<cfset vUnitTotal = qItems.Quantity * qItems.Price>
<cfset TotalPrice = TotalPrice + vUnitTotal>
<tr data-item-id="#qItems.ItemID#">
<td>#qItems.ItemDescription#</td>
<td><input type="text" name="Quantity_#qItems.LineID#" id="Quantity#vLineID#" class="Quantity" onchange="ChangePrice(#vLineID#,'Quantity');" value="#NumberFormat(qItems.Quantity, '9.99')#" </td>
<td><input type="text" name="Price_#qItems.LineID#" id="UnitPrice#vLineID#" class="Price" onchange="ChangePrice(#vLineID#,'UnitPrice');" value="#NumberFormat(qItems.Price, '9.99')#" </td>
<td id="UnitTotal#vLineID#" class="UnitTotal">#NumberFormat(vUnitTotal,'9.99')#</td>
</tr>
</cfloop>
</tbody>
<tfoot>
<td colspan="4"></td>
<td>Total:</td>
<td id="TotalPrice_Total">#NumberFormat(TotalPrice,'9.99')#</td>
</tfoot>
</table>
And here if the Jquery: The unit total is updating every time when Qty and Price is updated, however, RefreshTotals() function is not updating. Its getting me values but not adding them and calculating final total.
<script>
$(document).ready(function()
{
function ChangePrice(LineID,FieldChanged) {
var Quantity = document.getElementById("Quantity"+LineID);
var UnitPrice = document.getElementById("UnitPrice"+LineID);
var TotalPrice = 0;
var vQuantity = Quantity.value;
var vUnitPrice = UnitPrice.value;
if (FieldChanged == "Quantity" || FieldChanged == "UnitPrice") {
vCustomTotal = vQuantity * vUnitPrice;
$('#UnitTotal' + LineID).text(vCustomTotal.toFixed(2));
}
refreshTotals();
}
function refreshTotals() {
var vTotalPrice = 0;
$('.UnitTotal').each(function(index) {
var r = $("#tblUpdate.UnitTotal").text();
vTotalPrice = vTotalPrice + r;
});
$('#TotalPrice_Total').text(vTotalPrice.toFixed(2));
}
}
</script>

Consider the following example.
$(function() {
function formatCurrency(f) {
return "$" + parseFloat(f).toFixed(2);
}
function refreshTotals() {
var vTotalPrice = 0;
var r;
$(".UnitTotal").each(function(index, element) {
r = parseFloat($(element).text().trim().substring(1));
vTotalPrice += r;
});
$('#TotalPrice_Total').text(formatCurrency(vTotalPrice));
}
function changePrice(Row) {
var Quantity = parseInt($(".Quantity", Row).val());
var UnitPrice = parseFloat($(".Price", Row).val().substring(1));
var TotalPrice = Quantity * UnitPrice;
$(".UnitTotal", Row).html(formatCurrency(TotalPrice));
refreshTotals();
}
$(".Quantity, .Price").change(function() {
changePrice($(this).closest("tr"));
});
refreshTotals();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblUpdate" class="dataTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Unit Total</th>
</tr>
</thead>
<tbody>
<tr data-item-id="01">
<td>Item 01</td>
<td><input type="number" min="0" max="999" name="Quantity_01" id="Quantity01" class="Quantity" value="9" /></td>
<td><input type="text" name="Price_01" id="UnitPrice01" class="Price" value="$9.99" /> </td>
<td id="UnitTotal01" class="UnitTotal">$89.91</td>
</tr>
<tr data-item-id="02">
<td>Item 02</td>
<td><input type="number" min="0" max="999" name="Quantity_02" id="Quantity02" class="Quantity" value="6" /></td>
<td><input type="text" name="Price_02" id="UnitPrice02" class="Price" value="$8.88" /> </td>
<td id="UnitTotal01" class="UnitTotal">$53.28</td>
</tr>
<tr data-item-id="03">
<td>Item 03</td>
<td><input type="number" min="0" max="999" name="Quantity_03" id="Quantity03" class="Quantity" value="3" /></td>
<td><input type="text" name="Price_03" id="UnitPrice03" class="Price" value="$7.77" /> </td>
<td id="UnitTotal03" class="UnitTotal">$23.31</td>
</tr>
</tbody>
<tfoot>
<td colspan="2"></td>
<td>Total:</td>
<td id="TotalPrice_Total">$0.00</td>
</tfoot>
</table>
When there are changes to Quantity or Price, the total Unit Price is updated along with the Total. We can pass in the Row and then collect all the details needed from that Row. The value of an input is String so it is best to cast it into the proper Integer or Float as needed. This will ensure that Math operations are correct.

Related

JavaScript to add multiple decimal numbers and round the value after 0.59

Hi I have a script which will add multiple decimal numbers entered in input fields. But Here the value is rounding after 0.99 (like price of item). But I want to rounded it after 0.59. (like seconds).
Please Help me with this. Thanks in Advance.
$(document).ready(function(){
$(".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));
}
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
<tr>
<td>Sunday</td>
<td><input class="txt" type="text" name="txt"/></td>
</tr>
<tr>
<td>Monday</td>
<td><input class="txt" type="text" name="txt"/></td>
</tr>
<tr>
<td>Tuesday</td>
<td><input class="txt" type="text" name="txt"/></td>
</tr>
<tr>
<td>Wednesday</td>
<td><input class="txt" type="text" name="txt"/></td>
</tr>
<tr>
<td>Thrusday</td>
<td><input class="txt" type="text" name="txt"/></td>
</tr>
<tr>
<td>Friday</td>
<td><input class="txt" type="text" name="txt"/></td>
</tr>
<tr>
<td>Saturday</td>
<td><input class="txt" type="text" name="txt"/></td>
</tr>
<tr id="summation">
<td align="right">Sum :</td>
<td align="center"><span id="sum">0</span></td>
</tr>
</table>
var functionName=function(a){
var b=a-Math.floor(a);
if(b>0.59)
{
a=Math.floor(a)+1;
}
else
{
a=Math.floor(a);
}
return a;
}
And then in your script sum=functionName(sum);

Total sum of all multiplied values of textboxes

I want to multiply the textbox values and after multiplication sum of all answer values. Example:
SUM (NSP * Current Sales)
This program is working fine but when I change any value it adds the change not replace the values. It should replace the value of array.
And if possible, please minimize the code logic also. Thanks.
$(document).ready(function() {
var val1;
var val2;
var multi;
one();
second();
});
function one() {
$(document).on("change", ".qty1", function() {
var sumqty1 = 0;
sumqty1 += $(this).val();
val1 = sumqty1;
});
}
function second() {
$(document).on("change", ".qty2", function() {
var sumqty1 = 0;
var sumqty2 = 0;
sumqty1 += $(this).closest('tr').find('.qty1').val();
sumqty2 += $(this).val();
val1 = sumqty1;
val2 = sumqty2;
mul(val1, val2);
});
}
var arr = [];
function mul(a, b) {
var hh;
multi = a * b;
arr.push(multi);
var totalsum = 0;
for (var i in arr) {
var value = arr[i];
totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
$("#totalvalue").text(totalsum);
}
console.log(arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
You are continually adding new values into arr and there's a whole lot of shared mutable state going on here.
If there aren't that many rows in the table, you're best off just recalculating the whole total each time a value changes. Less risk of the data stepping on itself that way:
$(document).ready(function() {
$(document).on('change', '.qty1, .qty2', recalculate);
function getTotal() {
return $('#myTable tr')
.toArray()
.map($)
.map(function (row) {
return row.find('.qty1').val() * row.find('.qty2').val();
})
.filter(function (val) { return !Number.isNaN(val); })
.reduce(function (a, b) { return a + b; }, 0);
}
function recalculate() {
$("#totalvalue").text(getTotal());
}
});
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<table id="myTable" style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
</body>
</html>
Id say something like:
$(".qty1, .qty2").on("change", function(){
var qty2 = $(".qty2"),
total = 0;
$(".qty1").each(function(ind){
total += $(qty2[ind]).val() * $(this).val();
})
$("#totalvalue").text(total)
})
Added at the end of the document.
Edited a little
The way you have it right now, you're adding new elements to the array in the order they're created, which doesn't allow you to access them later to change them because they could be stored in any order.
The code below saves each value in the array based on the value of val1 so that each element has a designated place in the array. Because of that, you can update any of the values when they are changed, like so:
var arr = [];
function one() {
$(document).on("change", ".qty1", function() {
var sumqty1 = $(this).val();
});
}
function second() {
$(document).on("change", ".qty2", function() {
var val1 = $(this).closest('tr').find('.qty1').val();;
var val2 = $(this).val();
mul(val1, val2);
});
}
function mul(a, b) {
arr[a - 1] = a * b;
var totalsum = 0;
for (var i in arr) {
var value = arr[i];
totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
$("#totalvalue").text(totalsum);
}
console.log(arr);
}
$(document).ready(function() {
one();
second();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
I also took out some unnecessary code, including:
The hh declaration (since that variable isn't used) in your second() function
a couple of extraneous lines in your one() function
the multi variable
the sumqty1 and sumqty2 variables (you can just use val1 and val2)
Your val1 and val2 variables didn't need to be global, since you are only using them in one function and passing them as parameters to another.
You could also remove the one() function if you want, since those values seem to be static -- but I'm not sure if you allow that value to be changed in your original code.

Parsing input in javascript

I have a table for a school card.The aim is to display the average per grading period.The data is from the database while the average result is from the javascript.When a user input in any of the input fields, the average along that column should dynamically changes or update it.Now in my current code,It generates an error e.text() is not a function.Basically the sum variable didn't catch a value from the parseInt.Anyone have an idea resolving this issue?
****** sample results******
Subject | Col1 |Col2 |Col3 |Col4
1 80 80 86 80 (80+80+86+80)/4 Note: not this way
2 86 85 86 81
3 80 87 85 86
Result 82 84 and so on..
It should be:
(80+86+80)/3 number of rows
view.blade.php
<tr>
<th colspan="3">Subjects</th>
<th colspan="2">First Grading</th>
<th colspan="2">Second Grading</th>
<th colspan="2">Third Grading</th>
<th colspan="2">Fourth Grading</th>
</tr>
</thead>
<tbody>
#foreach($update_card['AllGrade'] as $subject)
{!! Form::hidden('grade_id[]',$subject['grade_id']) !!}
<tr>
<td colspan="3">{!! $subject->subject !!}</td>
<td colspan="2"><input type="text" name="term_1[]" value="{!! $subject->term_1 !!}" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_2[]" value="{!! $subject->term_2 !!}" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_3[]" value="{!! $subject->term_3 !!}" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_4[]" value="{!! $subject->term_4 !!}" class="form-control number-only"></td>
<td class="ave" value="0"></td>
</tr>
#endforeach
<tr id="average">
<td colspan="3">Average</td><td colspan="2">0</td> <td colspan="2">0</td> <td colspan="2">0</td> <td colspan="2">0</td>
</tr>
</tbody>
javascript here
$("input").on("keyup", function() {
$("tbody tr").each(function(index) {
var sum = 0; // The summation of all terms.
var card = 0; // Number of cells.
$(this).children('td').not(':first').each(function(i, e) {
card++;
sum+= parseInt(e.text().trim()); //this is the error
});
var avg = sum/card;
console.log(avg);
$("#average td:nth-of-type("+index+")").html(avg);
});
});
as I pointed you loop through tds and get text() while it has no text on it .. it
has an input so you need to get the input value not the td text
so you can try something like this
I create a functions for row_sum() to sum the row ,column_sum() to sum the column ,column_Average() to get column average by row numbers and row_Average() to get row average by td numbers.
$(document).ready(function(){
$("input").on("keyup", function() {
//row_sum(); // for sum row
//column_sum(); // for sum column
column_Average(); // for column average
row_Average(); // for row average
}).keyup(); // by adding .keyup() your code will run onload
});
function column_sum(){
var sum = []; // The summation of all terms.
$("tbody tr:not(#average)").each(function(index) {
var thisIt = $(this);
thisIt.find('td:not(.ave)').not(':first').each(function(i) {
var input_val = ($.trim($(this).find('input').val())) ? $(this).find('input').val().trim() : 0;
sum[i] ? sum[i] += parseInt(input_val) : sum.push(parseInt(input_val));
});
});
$('#average td:not(:first)').each(function(i){
$(this).text(sum[i]);
});
}
function row_sum(){
$("tbody tr:not(#average)").each(function(index) {
var thisIt = $(this);
var sum = 0; // The summation of all terms.
thisIt.find('td').not(':first').not(':last').each(function(i) {
var input_val = ($.trim($(this).find('input').val())) ? $(this).find('input').val().trim() : 0;
sum += parseInt(input_val);
});
thisIt.find('td.ave').text(sum);
});
}
function column_Average(){
var sum = []; // The summation of all terms.
var tr_num = $("tbody tr:not(#average)").length;
$("tbody tr:not(#average)").each(function(index) {
var thisIt = $(this);
thisIt.find('td:not(.ave)').not(':first').each(function(i) {
var input_val = ($.trim($(this).find('input').val())) ? $(this).find('input').val().trim() : 0;
sum[i] ? sum[i] += parseInt(input_val) : sum.push(parseInt(input_val));
});
});
$('#average td:not(:first)').each(function(i){
$(this).text(sum[i] / tr_num);
});
}
function row_Average(){
$("tbody tr:not(#average)").each(function(index) {
var thisIt = $(this);
var sum = 0; // The summation of all terms.
var code = 0; thisIt.find('td').not(':first').not(':last').each(function(i) {
var input_val = ($.trim($(this).find('input').val())) ? $(this).find('input').val().trim() : 0;
code++;
sum += parseInt(input_val);
});
thisIt.find('td.ave').text(sum / code);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th colspan="3">Subjects</th>
<th colspan="2">First Grading</th>
<th colspan="2">Second Grading</th>
<th colspan="2">Third Grading</th>
<th colspan="2">Fourth Grading</th>
<th>Average</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3">Subject</td>
<td colspan="2"><input type="text" name="term_1[]" value="12" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_2[]" value="13" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_3[]" value="14" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_4[]" value="15" class="form-control number-only"></td>
<td class="ave" value="0"></td>
</tr>
<tr>
<td colspan="3">Subject</td>
<td colspan="2"><input type="text" name="term_1[]" value="120" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_2[]" value="130" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_3[]" value="140" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_4[]" value="150" class="form-control number-only"></td>
<td class="ave" value="0"></td>
</tr>
<tr id="average">
<td colspan="3">Average</td><td colspan="2">0</td> <td colspan="2">0</td> <td colspan="2">0</td> <td colspan="2">0</td>
</tr>
</tbody>
</table>

Total value with jquery on table

I tried to calculate the total on the table using jquery, but when run totals do not appear. so I want to show the total live when I enter the input value, total auto-summing, what's wrong?
HTML
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong></td>
<td class="text-center"><strong>Value</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_a" name="producta" value="12.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_b" name="producta" value="19.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_c" name="producta" value="15.000"></td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong></td>
<td class="thick-line"><input type="text" id="total" name="total" /></td>
</tr>
</tbody>
</table>
JS
jQuery(document).ready(function(){
var total = ($('#product_a').val() + $('#product_b').val() + $('#product_c').val()) ;
$('#total').val(total);
});
You're doing it wrong. val() returns a string on an input[type=text] and currently you're just concatenating string values.
I want to show the total live when I enter the input value
Then, you need to add a listener when the inputs are being changed as you type. This could be done with keyup event.
E.g.
$(function() {
var $aProduct = $('#product_a'),
$bProduct = $('#product_b'),
$cProduct = $('#product_c'),
$total = $('#total'),
runTotal = function() {
var a = parseInt($aProduct.val()),
b = parseInt($bProduct.val()),
c = parseInt($cProduct.val());
$total.val(a + b + c);
};
$('.inputVal').on('keyup', runTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong>
</td>
<td class="text-center"><strong>Value</strong>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_a" name="producta" class="inputVal" value="12.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_b" name="productb" class="inputVal" value="19.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_c" name="productc" class="inputVal" value="15.000">
</td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong>
</td>
<td class="thick-line">
<input type="text" id="total" name="total" />
</td>
</tr>
</tbody>
</table>
Hi try following code....
jQuery(document).ready(function(){
$("input").on("change",updateTotal); // this will total on change input.
updateTotal(); //this will total on start..
});
function updateTotal()
{
var total = ($('#product_a').val()*1 + $('#product_b').val()*1 + $('#product_c').val()*1) ;
//By multiplying 1 to any string format number it will convert to number datatype.
//var total = (Number($('#product_a').val()) + Number($('#product_b').val()) + Number($('#product_c').val()));
//You can also uncomment above line to get your desire output.
$('#total').val(total);
}

Using the same jQuery in multiple operations

I have a small question and I hope someone can help me with it :D
I’m trying to create a product table, in which a user just add the quantity of a product and the jquery makes the multiplication to its value and gives the result
I already made this, and it works well:
<script>
$(document).ready(function(){
$('#quantity_1').keyup(function(){
var price_1 = $("#price_1").val();
var quantity_1 = $("#quantity_1").val();
quantity_1 = quantity_1.replace(/[^0-9]+/g, '');
$("#quantity_1").val(quantity_1);
var total_1 = price_1 * quantity_1;
$( "#total_1" ).val( total_1.toFixed(2) );
});
});
</script>
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
</table>
Working demo here:
http://jsfiddle.net/EnterateNorte/9kswL0gf/
But I would like to be able to add more than one line, like so:
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Name 1</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
<tr>
<td>Name 5</td>
<td><input type="hidden" name="product[5][price]" id="price_5" value="10.00" />23.00</td>
<td><input type="text" name="product[5][quantity]" id="quantity_5" /></td>
<td><input type="text" name="product[5][total]" id="total_5" value="0" /></td>
</tr>
<tr>
<td>Name 3</td>
<td><input type="hidden" name="product[3][price]" id="price_3" value="130.00" />10.00</td>
<td><input type="text" name="product[3][quantity]" id="quantity_3" /></td>
<td><input type="text" name="product[3][total]" id="total_3" value="0" /></td>
</tr>
<tr>
<td>Name 4</td>
<td><input type="hidden" name="product[4][price]" id="price_4" value="12.00" />10.00</td>
<td><input type="text" name="product[4][quantity]" id="quantity_4" /></td>
<td><input type="text" name="product[4][total]" id="total_4" value="0" /></td>
</tr>
</table>
And if it isn’t to much trouble, I would be awesome if it would SUM all the totals and show a gran total at the end of the table :)
Use:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var price = $(this).parent().prev().find('input').val();
var quantity = $(this).val();
var total = price * quantity;
$(this).parent().next().find('input').val( total.toFixed(2) );
});});
Working Demo
Update: For showing Grand Total
var sum = 0;
//iterate through each textboxes and add the values
$('[name*=total]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseInt(this.value);
}
});
Working Demo
What you can do is to find the elements using their relative position instead of hard coded ids
$(document).ready(function () {
$('input[id^="quantity_"]').keyup(function () {
var $tr = $(this).closest('tr');
var price = $tr.find('input[id^="price_"]').val();
var quantity = this.value;
var total = (price * quantity) || 0;
$tr.find('input[id^="total_"]').val(total.toFixed(2));
});
});
Demo: Fiddle
I've updated your code in Fiddle. You need to change in your markup a bit.
<tr>
<td>Product Name</td>
<td><input type="hidden" class="price" ... />10</td>
<td><input type="text" class="quantity" ... /></td>
<td><input type="text" class="total" ... /></td>
</tr>
$(document).ready(function(){
$('.quantity').keyup(function(){
var parent = $(this).closest("tr");
var price = $(".price", parent).val();
var quantity = $(".quantity", parent).val();
var total = price * quantity;
$(".total", parent).val(total.toFixed(2));
});
});
I would recommend you to use common class
HTML:
<tr>
<td>Name 5</td>
<td>
<input type="hidden" class="price" value="10.00" />10.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
<tr>
<td>Name 3</td>
<td>
<input type="hidden" class="price" value="130.00" />130.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
Script:
$('.quantity').keyup(function () {
var tr = $(this).closest('tr');
var price = tr.find('.price').val();
var quantity = $(this).val();
var total = price * quantity;
tr.find('.total').val(total.toFixed(2));
});
DEMO
Modify your table:
<table border="1" cellpadding="5px" cellspacing="0" id='table' >
<!-- your rows with inputs -->
<tr>
<td>
<input id='totalSum' value='0' type='text' />
</td>
</tr>
</table>
Make all your 'total' inputs readonly by adding 'readonly' attribute.
js code:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var total = 0;
$('#table tr').each(function(i,item){
var price = parseFloat($(item).find('[name*=price]').val().replace(',','.'));
var quantity = parseInt($(item).find('[name*=quantity]').val());
if(!isNaN(price) && !isNan(quantity)){
total += price*quantity;
}
});
$("#totalSum").val(total.toFixed(2));
});
});

Categories

Resources