I setup a simple checkout with increment/subtract buttons (function calculates total price -> price * quantity) and now struggling getting the variable with the total amount out of that function. As a result I need the total amount (in the functions it's total1 or total2) in the global variable total. In my example it doesn't work, because calling the function incr() or subt() for the variable total triggers the function and adds or increment the value of the value again. This is what I have so far:
<script>
var quantity = document.getElementById("qty").value;
var counter = document.getElementById("qty").value;
// subtract function triggered by subtract button
function subt(){
var quantity = document.getElementById("qty").value = --counter;
document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var total1 = document.getElementById('current').innerHTML = quantity * 298;
return total1;
}
// increment function triggered by increment button
function incr(){
var quantity = document.getElementById("qty").value = ++counter;
document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var total2 = document.getElementById('total').innerHTML = quantity * 298;
return total2;
}
var total = incr();
</script>
This is what my code looks now:
var counter = 1;
var quantity = document.getElementById("qty").value;
var initial = document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var add = document.getElementById("add");
var sub = document.getElementById("sub");
add.addEventListener("click", function(e) {
calcFunc(1);
});
sub.addEventListener("click", function(e) {
calcFunc(-1);
});
function calcFunc(operation) {
quantity = operation < 0 ? --counter : ++counter;
document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var total = document.getElementById('current').innerHTML = quantity * 298;
return total;
}
I think #epascarello means to create one function that get's a parameter passed to it [-1 or 1] in this case depending on if the add or subtract button is pressed.
I've been taught that you should avoid solutions using parameterless functions with no options it creates long drawn out code.
Example below:
var total = null;
addFoo.addEventListener("click", function(e) {
total = calcFunc(1);
});
minusFoo.addEventListener("click", function(e) {
total = calcFunc(-1);
});
function calcFunc(operation) {
quantity = operation < 0 ? --counter : ++counter;
document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var total = document.getElementById('current').innerHTML = quantity * 298;
return total;
}
I'm not quite sure what this is going to do though... :(
Is this what you had in mind #epascarello?
Related
I've got a form which utilizes some checkbox inputs with fixed values and a text 'number' input which should be calculated against an hourly rate.
The idea is that we can select pre-set values and display the total including the number of billable hours times the hourly rate.
<script>
$( document ).ready(function() {
var sum = 0;
var origsum = 0;
var newsum = 0;
var tax = 0.06;
var hourly = 250;
var tothours = 0;
$('.cost').click(function() {
var total = parseInt($('#total').val());
if($(this).is(':checked')) {
sum = total + parseInt($(this).val());
} else {
sum = total - parseInt($(this).val());
}
$('#total').val(sum);
});
$('.tax').click(function() {
var total = parseInt($('#total').val());
if($(this).is(':checked')) {
origsum = sum;
newsum = total + (tax * parseInt(sum));
} else {
newsum = total - (tax * parseInt(sum));
}
$('#total').val(newsum);
});
var prevCount = 0;
var newCount = 0;
$(document).on('keyup mouseup', '.rate', function() {
newCount = parseInt($('.rate').val());
total = parseInt($('#total').val());
if(newCount > prevCount) {
$('.cost').each(function() {
if($(this).is(':checked')) {
sum = total + hourly;
$('#total').val(sum);
return false;
}
else {
$('#total').val($('.rate').val() * hourly);
}
});
}
else {
$('.cost').each(function() {
if($(this).is(':checked')) {
sum = total - hourly;
$('#total').val(sum);
return false;
}
else {
$('#total').val($('.rate').val() * hourly);
}
});
}
prevCount = parseInt($('.rate').val());
});
});
</script>
The best way to explain it is by example, so I created this fiddle which includes the script and html:
https://jsfiddle.net/dfkw4ggt/4/
As you'll see when you poke around (thanks in advance, btw!), it's all fairly well working until we start adding/clicking in the text/numeric field.
Any advice and/or pointers would be greatly appreciated as I've about exhausted my researching this and would love to get it working.
Here's my take, and my opinion.
I think you should have a Sub-Total, Total, and Tax. (You could still hide these fields from the end users and only show the "Total")
You can also simplify your code a bit to make it easier to find errors.
Take a look at this fork of your fiddle, where I changed your JS code and added sub/tax/total. Notice how, if there are errors in the calculations, it will be easier to find now.
The JS:
var taxRate = 0.06;
var hourly = 250;
// we really only need one event listener for the whole page
$(document).on("change", "input", updateTotal);
function updateTotal() {
var runningTotal = 0;
// find all checked cost fields
$(".cost:checked").each(function(){
runningTotal += parseInt($(this).val());
});
var billableAmount = parseInt($(".rate").val()) * hourly;
runningTotal += billableAmount;
$("#subtotal").val(runningTotal);
var tax;
if ($(".tax").prop("checked")) {
tax = runningTotal * taxRate;
} else {
tax = 0;
}
$("#taxAmt").val(tax);
$("#total").val( runningTotal + tax );
}
I was trying to develop a checkbox using jQuery ..where oncheck total will be updated but when i uncheck it will be back as it is.. Here total updated with oncheck but it don't get back to total amount when i uncheck it .what could be possible error..anyone help please?
$('#vat').on('click',function(e){
var vat = document.getElementById("vat").value;
var total = document.getElementById("total").value;
var sum = +total + +vat;
document.getElementById("total").value = sum;
});
Assume #vat is your input id
1- You need to use change instead of click for radio and checkbox inputs
2- check if checked or not by using this.checked
$('#vat').on('change',function(e){
var sum = 0;
var vat = document.getElementById("vat").value;
var total = document.getElementById("total").value;
if(this.checked === true){
sum = total + vat;
}else{
sum = total - vat;
}
document.getElementById("total").value = sum;
});
And while you're using and tagged jquery
$('#vat').on('change',function(e){
var sum = 0;
var vat = parseInt($(this).val());
var total = parseInt($("#total").val());
if(this.checked === true){
sum = total + vat;
}else{
sum = total - vat;
}
$("#total").val(sum);
});
I have the following jquery function that adds up 7 textboxes and puts the total in a grand total textbox:
$(document).ready(function() {
$('.class2').keyup(function() {
var sum = 0;
$('.class2').each(function() {
sum += Number($(this).val());
});
$('#GrandTotal').val((sum).toFixed(2));
});
});
The 7 textboxes are populated by another function. When a quantity is entered, those textboxes are auto populated by the quantity times the price. The problem I am having is that the grand total textbox is not being populated until you tab out of the textbox that has the calculated price. However, if I enter the price directly into the textbox (without using the quantity), the grand total textbox updates immediately. Is there something that I can do that will update the grand total textbox after I enter a quantity? The page is at www.pfacmeeting.org/badgeform2.php. Thanks for any help with this.
-cdr6800
When you auto-populate the textboxes, try triggering the keyup event, using .trigger() function:
$(".class2").trigger("keyup");
You should change your script to:
$('input[name="BadgeQuantity"]').keyup(function(){
var a = 50;
var b = $(this).val();
$('input[name="BadgeTotal"]').val((a * b).toFixed(2));
$(".class2").trigger("keyup");
});
$('input[name="ThursdayBreakfast"]').keyup(function(){
var a = 42;
var b = $(this).val();
$('input[name="ThursdayBreakfastTotal"]').val((a * b).toFixed(2));
$(".class2").trigger("keyup");
});
$('input[name="ThursdayLunch"]').keyup(function(){
var a = 53;
var b = $(this).val();
$('input[name="ThursdayLunchTotal"]').val((a * b).toFixed(2));
$(".class2").trigger("keyup");
});
$('input[name="FridayBreakfast"]').keyup(function(){
var a = 42;
var b = $(this).val();
$('input[name="FridayBreakfastTotal"]').val((a * b).toFixed(2));
$(".class2").trigger("keyup");
});
$('input[name="FridayLunch"]').keyup(function(){
var a = 53;
var b = $(this).val();
$('input[name="FridayLunchTotal"]').val((a * b).toFixed(2));
$(".class2").trigger("keyup");
});
$('input[name="FridayDinner"]').keyup(function(){
var a = 115;
var b = $(this).val();
$('input[name="FridayDinnerTotal"]').val((a * b).toFixed(2));
$(".class2").trigger("keyup");
});
$('.DrawingTickets').change(function(){
var selectedValue = parseFloat($(this).val());
$('#DrawingTicketsTotal').val((selectedValue).toFixed(2));
$(".class2").trigger("keyup");
});
$('.class2').keyup(function() {
var sum = 0;
$('.class2').each(function() {
sum += Number($(this).val());
});
$('#GrandTotal').val((sum).toFixed(2));
});
I have this complicated JS function that must calculate the sum of product single price * qty and if there are available options for the product and if the available options have extra tax it has to be added also to the total.
function update_amounts() {
var sum = 0.0;
$('#basketorder > tbody > .product').each(function () {
var qty = $(this).find('.qty option:selected').val();
var selectedoptaddtax = 0.0;
$('.selectedoptionselect option:selected').each(function () {
var selectedoptaddtax = $(this).attr('price');
})
var price = $(this).find('.price').val();
var amount = ((qty * price) + selectedoptaddtax);
sum += amount;
$(this).find('.amount').text('' + amount);
});
$('.total').text(sum);
}
I have prepared jsfiddle here
In the example I have only 1 product in the basket, but the function must calculate correct if more that 1 product in the basket.
$(document).ready(function () {
update_amounts();
$('.qty').change(function () {
update_amounts();
});
$('.selectedoptionselect').change(function () {
update_amounts();
});
});
You need to add selected option prices.
Code
$(document).ready(function () {
$('.selectedoptionselect, .qty').change(function () {
update_amounts();
}).change();
});
function update_amounts() {
var sum = 0.0;
$('#basketorder > tbody > .product').each(function () {
var qty = $(this).find('.qty').val();
var selectedoptaddtax = 0.0;
//Use find here
$(this).find('.selectedoptionselect option:selected').each(function () {
selectedoptaddtax += +$(this).attr('price'); // You need to add price
})
var price = $(this).find('.price').val();
var amount = (qty * price) + (qty * selectedoptaddtax); //Changes here
sum += amount;
$(this).find('.amount').text('' + amount);
});
$('.total').text(sum);
}
DEMO
For some reason i can't get the variable 'total' to define at all...
I defined it on like 74 but it does't want to stick for some reason.. what am i doing wrong? Thanks in advance!
$(document).ready(function() {
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(".tab-content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab-content:first").show(); //Show first tab content
$('.question-form-submit').click(function(e) {
e.preventDefault();
var activeTab = '#'+$(this).attr('name');
var activeClass = activeTab.substr(5);
$("ul.tabs li").removeClass("active");
$('ul li:nth-child('+activeClass+')').addClass("active"); //Add "active" class to selected tab
$(".tab-content").hide(); //Hide all tab content
$(activeTab).fadeIn(); //Fade in the active ID content
$('.meter-value').removeClass('meter-width');
switch (activeClass) {
case '2' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 46.5%;');
break;
case '3' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 67%;');
break;
case '4' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 100%;');
break;
}
return false;
});
$('.quantity, .init_cost').change(function() {
var row_id = $(this).attr('id');
var row_number = row_id.substr(9);
var item_cost = $('#cost_'+row_number).attr('value');
var item_quantity = $('#quantity_'+row_number).attr('value');
var final_cost = item_cost * item_quantity;
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
});
$('.row input').each(function(index) {
var row_id = $(this).attr('id');
var row_number = row_id.substr(9);
var item_cost = $('#cost_'+row_number).attr('value');
var item_quantity = $('#quantity_'+row_number).attr('value');
var final_cost = item_cost * item_quantity;
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
});
var total = 0;
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
var total = total + final_cost;
console.log(total);
})
});
The inner declaration on the line var total = total + final_cost; hides the outer declaration from the line var total = 0;.
The total in the each function is shadowing the outer one.
A simpler example of the same thing is here:
(function()
{
var total = 1;
console.log("total 1: " + total);
(function()
{
console.log("total 2: " + total);
var total = total + 3;
console.log("total 3: " + total);
})()
})();
In addition to the shadowing, you have to consider hoisting. Because the inner var is hoisted to the top, the inner function is roughly equivalent to:
function()
{
var total = undefined;
console.log("total 2: " + total);
total = total + 3;
console.log("total 3: " + total);
}
In this case, I think you simply don't want the inner var keyword. In other cases, you would use a different variable name.
You're redefining total every time you loop through
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
var total = total + final_cost;
console.log(total);
})
Why not try this?
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
total = total + final_cost;
console.log(total);
})
Try to remove second var before the total.
total = total + final_cost;
That's because you declare the variable two times (everytime you write var total it's declared anew. So you have one outside of the "final_cost" function and one inside, which is set to total from outside + final_cost. So in effect you always log the value of final_cost.
Just write total = total + final_cost; and it should work.
Syntax error, killing your script:
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
^--- extra ;
Next time, check your browser's console (shift-ctrl-J in FF/Chrome) for errors. Things like this are reported instantly.
I'd replace the line:
var total = total + final_cost;
with:
total += final_cost
Not sure about this answer but, try defining the variable total first with a default value like 0 and then use the total + final_cost operation.
var total = 0;
total += final_cost;
why is that? when you declare the total without a default value, the value will be "undefined" so the javascript will represent the following as :
var total = "undefined" + final_cost;
I guess that's the error.