Reputation: 65
I'm trying to sum up my checked checkboxes and inputs with values in them. Currently I'm getting both separately (and it functions how I want it to) like this:
$(document).ready(function() {
$('.box').change(function(){
var totalbox = 0;
$('.box:checked').each(function(){
totalbox+= +($(this).attr("rel"));
});
$('#totalbox').val(totalbox.toFixed(2));
});
});
$(document).on("recalc", ".vendor_accounts", function () {
var totalinput = 0;
$(this).find(".payment").each(function () {
totalinput += +$(this).val();
});
$("#totalinput").val(totalinput.toFixed(2));
});
$(".vendor_accounts").trigger("recalc");
The above functions produce the right results separately. I just need to combine the values of those results and display them as one var inside an id.
Per the below answer, this is what did the trick:
function updateGrandTotalDisplayed(val){
var input1 = parseFloat($('#checkTotal').val());
var input2 = parseFloat($('#inputTotal').val());
var total = input1 + input2;
$('#totalPrice').val(total.toFixed(2));
};
Upvotes: 0
Views: 65
Reputation: 574
One solution would be to place a total
variable in a scope that's available to both of the functions that calculate a total. For instance, before all of your code, you can write:
var grandTotal = 0;
Then you can add each subtotal to the grandTotal
variable when that subtotal is calculated. If you are displaying the total somewhere on the page, you could also call a function at that point to update the displayed total. So for example, in the first part, you can change it like so:
$(document).ready(function() {
$('.box').change(function(){
var total = 0;
$('.box:checked').each(function(){
total+= +($(this).attr("rel"));
});
$('#total').val(total.toFixed(2));
grandTotal += total;
updateGrandTotalDisplayed();
});
});
(The updateGrandTotalDisplayed()
would be a function you write elsewhere, and call here to update what is displayed on the page.) Hope this helps.
EDIT to add: If you just wish to sum the values without using a third variable, you can use the val()
function to retrieve the values, and then add them together. For example, $('#totalinput').val()
will give you the current value inside the #totalinput
element.
However, you should note that you cannot rely on the two subtotals being calculated in a specific order. You don't know which calculation will happen or finish first.
Upvotes: 1