Calculate total value using jquery - javascript

I have a table like below :
<table>
<th>Sl No</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount %</th>
<th>Total Price</th>
<tr>
<td>1</td>
<td><input class="expensess" ></input></td>
<td><input class="expensess" ></input></td>
<td><input class="expensess" ></input></td>
<td><input class="expensess_sum"></input></td>
</tr>
<tr>
<td>2</td>
<td><input class="expensess" ></input></td>
<td><input class="expensess" ></input></td>
<td><input class="expensess" ></input></td>
<td><input class="expensess_sum"></input></td>
</tr>
</table>
Grand Total = <input id="grand_total">
I am trying to display the Total Price of each row using jquery keyup function.
and also want to display the grand total price of the each row.
the formula of finding the Total Price is given below :
discount_value = Price*(discount_percent/100)
discount_price = Price-discount_value
total_price = discount_price * quantity
How can I do this please help
i am trying simply just summing all value like this :
<script type="text/javascript">
$(document).ready(function(){
$(".expensess").each(function() {
$(document).on('keyup', '.expensess', function() {
sum($(this).parents("tr"));
});
});
});
function sum(parent){
var sum = 0;
$(parent).find(".expensess").each(function(){
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$(parent).find(".expensess_sum").val(sum.toFixed(2));
}
</script>
But m confused how to implement the above formula for calculate the total price.

$('input.qty,input.price,input.discount').on('change keyup',function(){
var $tr = $(this).closest('tr'),
$qty = $tr.find('input.qty') ,
$price= $tr.find('input.price'),
$discount= $tr.find('input.discount'),
$total= $tr.find('input.expensess_sum'),
$grand_total=$('#grand_total');
$total.val($qty.val()*($price.val()-($price.val()*($discount.val()/100))));
var grandTotal=0;
$('table').find('input.expensess_sum').each(function(){
if(!isNaN($(this).val()))
{grandTotal += parseInt($(this).val());
}
});
if(isNaN(grandTotal))
grandTotal =0;
$grand_total.val(grandTotal)
})
input{
width:80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table>
<tbody><tr>
<th>Sl No</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount %</th>
<th>Total Price</th>
</tr>
<tr>
<td>1</td>
<td><input class="expensess qty"></td>
<td><input class="expensess price"></td>
<td><input class="expensess discount"></td>
<td><input class="expensess_sum" disabled=""></td>
</tr>
<tr>
<td>2</td>
<td><input class="expensess qty"></td>
<td><input class="expensess price"></td>
<td><input class="expensess discount"></td>
<td><input class="expensess_sum" disabled=""></td>
</tr>
</tbody></table>
Grand Total = <input id="grand_total" disabled="">
</body>

Did it by using simple java script Code!
var sumExpenses = 0;
var tdBudget = document.getElementById('tableBudget').getElementsByTagName('td');
for (var i = 0; i < tdBudget.length; i++) {
if (tdBudget[i].className == "spanexpense") {
sumExpenses += isNaN(tdBudget[i].innerHTML) ? 0 : parseInt(tdBudget[i].innerHTML);
}
}
document.getElementById('sumExpenses').innerHTML = sumExpenses;
<table class="table table-bordered">
<thead>
<tr>
<td class="label-title">Value</td>
<td class="label-title">Value</td>
<td class="label-title">Value</td>
</tr>
</thead>
<tbody id="tableBudget">
<tr>
<td class="spanexpense">
12
</td>
<td class="spanexpense">
23
</td>
<td class="spanexpense">
23
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td id="sumExpenses"></td>
</tr>
</tfoot>
</table>
Fiddle https://jsfiddle.net/ey2gLp7t/

Related

Getting error while compare with constant value (+10 or -10) with same currency using jQuery

Have requirement like I need to compare one threshold value with sum of the total value (count) and will compare like based on threshold if threshold value +10 or -10 and selected records have same currency. Need to do the successful validation. If beyond more than +10 or -10 not allowed to success validation.
Script is failing if differnece is in negetive values(-) and its giving validation alert if its differnce is at positive values(-). Please sugges me the solution
$(document).ready(function() {
var theresholdVal = "10";
$('input[type="checkbox"]').on('change', function() {
var creditAmount = 0;
$("#firstTable input:checked").each(function() {
//get td(amount column value)
var values = $(this).closest("tr").find("td:eq(1)").text()
if (values != "") {
creditAmount += parseFloat(values);
}
});
$("#secondTable input:checked").each(function() {
//get td(amount column value)
var values = $(this).closest("tr").find("td:eq(1)").text()
if (values != "") {
creditAmount += parseFloat(values);
}
});
$("#idCheckBoxLabel").text(creditAmount);
})
$("#idMatch").click(function() {
var countVal = $("#idCheckBoxLabel").text();
var jsonData1 = [];
var jsonData2 = [];
var $headers = $("#firstTable").find("th:not(:first)");
var $rows = $("#firstTable").find("tbody tr input[type=checkbox]:checked").each(function(index) {
const $cells = $(this).closest("tr").find("td:not(:first)");
jsonData1[index] = {};
$cells.each(function(cellIndex) {
jsonData1[index][$($headers[cellIndex]).text()] = $(this).text();
});
});
var $headers = $("#secondTable").find("th:not(:first)");
var $rows = $("#secondTable").find("tbody tr input[type=checkbox]:checked").each(function(index) {
const $cells = $(this).closest("tr").find("td:not(:first)");
jsonData2[index] = {};
$cells.each(function(cellIndex) {
jsonData2[index][$($headers[cellIndex]).text()] = $(this).text();
});
});
console.clear()
//loop through json arrays
for (let i = 0; i < jsonData1.length; i++) {
for (let j = 0; j < jsonData2.length; j++) {
console.log(jsonData1[i]['Currency'] + "--" + jsonData2[j]['Currency'])
//check currency keys..
if (jsonData1[i]['Currency'] !== jsonData2[j]['Currency']) {
alert("Currency is mismatched, please select same currency!!!");
return false;
} else if (parseFloat(theresholdVal) <=
countVal + parseFloat(theresholdVal) &&
parseFloat(theresholdVal) <=
countVal - parseFloat(theresholdVal)) {
alert("Selected value is more thereshold value");
return false;
}else{
alert("Data matched successfully!!!");
}
}
}
$("#firstTable tbody input:checked").each(function() {
if ($("#secondTable tbody tr td input").is(":checked")) {
$("#secondTable").find("tbody tr input[type=checkbox]:checked").prop({
disabled: true,
});
$(this).prop({
disabled: true
});
$(this).closest("tr").css("background-color", "grey !important;");
}
});
});
});
td{
border:1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="idMatch">Match</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div>
<div>Count::<span id="idCheckBoxLabel"></span>
<div>
<div>
<table datatable id="firstTable" [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th><input type="checkbox"></th>
<th>Amount</th>
<th>Currency</th>
<th>Nation</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-40</td>
<td>USD</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-30</td>
<td>USD</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-85</td>
<td>USD</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>67</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>10</td>
<td>IND</td>
<td>xyz</td>
</tr> <tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>20</td>
<td>IND</td>
<td>xyz</td>
</tr> <tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>55</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>55</td>
<td>IND</td>
<td>xyz</td>
</tr> <tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>55</td>
<td>IND</td>
<td>xyz</td>
</tr> <tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>55</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-100</td>
<td>USD</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>89</td>
<td>EUR</td>
<td>xyz</td>
</tr>
</tbody>
</table>
<table datatable id="secondTable" [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th><input type="checkbox"></th>
<th>Amount</th>
<th>Currency</th>
<th>Nation</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>111</td>
<td>EUR</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>22</td>
<td>USD</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>90</td>
<td>DNR</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>22</td>
<td>USD</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>55</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-30</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-20</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-10</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>10</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-40</td>
<td>IND</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>-45</td>
<td>IND</td>
<td>xyz</td>
</tr>
</tbody>
</table>
</div>
</div>

Angualr Datatables: How to get sum of selected column values dynamically using javaScript

Have one table, and if we checkbox checked amount values automatically sum and displayed on top. Tried below code, its getting values but not getting exact sum values. Could you pls suggest the what is the issue..
checkboxCheckCount(info: any): void {
var creditAmount = 0;
$("#firstTable input:checked").each(function() {
alert(info.index);
if (info.index != "") {
creditAmount += parseFloat(info.index);
} else {
creditAmount = creditAmount;
}
});
Stackblitz
As you are already using each loop to iterate through your checked checkboxes you can use $(this).closest("tr").find("td:eq(1)") this will give you amount column td value and then you can pass same to your creditAmount.
Demo Code :
$('input[type="checkbox"]').on('change', function() {
var creditAmount = 0;
$("#firstTable input:checked").each(function() {
//get td(amount column value)
var values = $(this).closest("tr").find("td:eq(1)").text()
if (values != "") {
creditAmount += parseFloat(values);
}
});
$("#idCheckBoxLabel").text(creditAmount);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div>
<div>Count::<span id="idCheckBoxLabel"></span>
<div>
<div>
<table datatable id="firstTable" [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th><input type="checkbox"></th>
<th>Amount</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>1</td>
<td>Abc</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>2</td>
<td>Abc</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>3</td>
<td>Abc</td>
<td>xyz</td>
</tr>
</tbody>
</table>
</div>
</div>

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

Get sum of a column in a table

Suppose i have the table below and i want to add the column Credits to get its sum
<table id="tbl_semester11">
<thead>
<tr>
<th>Semester 1</th>
</tr>
</thead>
<thead>
<tr>
<th>Module Code</th>
<th>Module Name</th>
<th>Credits</th>
<th>Module %</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>MGMT1101C</td>
<td>Management Seminar</td>
<td id="txtcredit112" class="sum">3</td>
<td><input type="number" id="txtpercentage112" min="40" max="100" onchange="process([1,1,2,5]);"></td>
<td id="txtgrade112">D</td>
</tr>
<tr class="alt">
<td>HCA1105C</td>
<td>Computer Architecture</td>
<td id="txtcredit113" class="sum">4</td>
<td><input type="number" id="txtpercentage113" min="40" max="100" onchange="process([1,1,3,5]);"></td>
<td id="txtgrade113">D</td>
</tr>
<tr>
<td>PROG1115C</td>
<td>Object Oriented Software Development I</td>
<td id="txtcredit114" class="sum">4</td>
<td><input type="number" id="txtpercentage114" min="40" max="100" onchange="process([1,1,4,5]);"></td>
<td id="txtgrade114">D</td>
</tr>
<tr class="alt">
<td>MATH1103C</td>
<td>Decision Mathematics</td>
<td id="txtcredit115" class="sum">3</td>
<td><input type="number" id="txtpercentage115" min="40" max="100" onchange="process([1,1,5,5]);"></td>
<td id="txtgrade115">D</td>
</tr>
<tr>
<td>ITE1107C</td>
<td>Language and Communication Seminar</td>
<td id="txtcredit116" class="sum">3</td>
<td><input type="number" id="txtpercentage116" min="40" max="100" onchange="process([1,1,6,5]);"></td>
<td id="txtgrade116">D</td>
</tr>
<tr class="al">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td bgcolor="#b3ffb3"><b>S.P.A</b></td>
<td bgcolor="#4dff4d" id="spa11">40.7</td>
</tr>
</tbody>
</table>
Here is my JS
function getsum(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + '.sum').each(function () {
sum += +(this).text()||0;
});
return sum;
arr is the same parameter as process i.e [1,1,3,5].The problem is that sum always returns 0
Your selector is wrong. If you want to select children with the .sum class, you should add a space between parent and children. Your function should be:
function getsum(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' .sum').each(function () {
sum += parseInt($(this).text())||0;
});
return sum;
}
Also, I used parseInt() because .text() returns a string. That way you are sure to have a NaN value or an actual integer.

Automatically calculate value of jquery spinner

Actually how to automatically calculate subtotal depending the js spinner change, also sum them into grand total with jquery, I am newly to the jquery with operation function so any suggestion will be appreciated
Thanks
Warmly
Fiddle >>
<div class="table-responsive" id="bottom-table">
<table class="table table-striped">
<thead>
<tr>
<th>No</th>
<th>Part Number</th>
<th>Desc</th>
<th>Qty / Unit</th>
<th>Qty Needed</th>
<th>Het ( Rp )</th>
<th>Estimation Price</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>3DCam01</td>
<td>3D Camera</td>
<td>1</td>
<td><input class="spinner" value="1" readonly="readonly"></td>
<td>$1500.00</td>
<td><p class="subtotal"></p>Subtotal</td>
<td>Delete</td>
</tr>
<tr>
<td>2</td>
<td>USB02</td>
<td>External Hard Drive</td>
<td>1</td>
<td><input class="spinner" value="1" readonly="readonly"></td>
<td>$800.00</td>
<td>Subtotal</td>
<td>Delete</td>
</tr>
<tr>
<td>3</td>
<td>wristWear03</td>
<td>Wrist Watch</td>
<td>1</td>
<td><input class="spinner" value="1" readonly="readonly"></td>
<td>$300.00</td>
<td>Subtotal</td>
<td>Delete</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Total</td>
<td>Total Amount</td>
<td>Delete</td>
</tr>
</tbody>
</table>
</div>
Thanks
Warmly
you need to bind to the spin event to get the value entered then update the DOM accordingly
function quantity(price, multiplier) {
if (multiplier === 1) {
return '$' + price.toFixed(2);
}
return '$' + (price * multiplier).toFixed(2);
}
$( ".spinner" ).spinner({
min: 1,
spin: function (event, ui) {
var value = ui.value;
var $target = $(event.target);
var $priceCell = $target.parents('td').next('td');
var $subtotalCell = $priceCell.next('td');
$subtotalCell.text(quantity($priceCell.data('price'), value));
}
});
fiddle - http://jsfiddle.net/m6csdx51/1/
notice the addition of data-price to the price cells

Categories