I am trying to calculate the total of a selection of CDs in addition of P&P. The code I'm using is coming to a total of NaN?
Very confused here. what am I doing wrong?
function calculateTotal() {
var Collection method = document.getElementById('collection').value +
var select CDs = document.getElementById('selectCD').value;
var total = document.getElementById('total');
total.value = 'collection'(total) + 'selectCD'(total);
}
Here is a JSFiddle with the full code.
In your fiddle collection and selectCD are divs (not inputfields) containing inputfields. You can't do divElm.value.
Then the php-code in your fiddle would normally be able to output more then one cd, so you'd need to add the totals of the selected cd's to.
The minimum changes needed to get your code working are:
function calculateTotal(){
var coll = document.getElementsByName('deliveryType'),
cds = document.getElementsByName('cd[]'),
cdTot = 0,
L = coll.length;
while(L--){if(coll[L].checked){ //get shipping costs
coll=Number(coll[L].getAttribute('title')); break;
} }
L=cds.length;
while(L--){if(cds[L].checked){ //add total prices
cdTot += Number(cds[L].getAttribute('title'));
} }
// output total
document.getElementById('total').value = coll + cdTot;
}
Also you'd want to set some more triggers to function calculateTotal (from the shipping costs and selected cd's; this way, if they change, the total-field will update to).
See this working fiddle with these changes (and some other fixes) based on your fiddle so you can get motivated seeing it (calculation) in action.
However I do hope this is for a school-question and not for a live webshop. I would re-think my strategy as I think you are currently working your way to a big security hole.
Good luck!
Related
I have a simple jquery script that allows users to see total prices for the services they select on a form via checkboxes.
The price calculator is simple and works alright. However, whenever there is a trailing zero on the end of a price (ex. 14.90) it does not calculate and instead concats to the end of the price (rather it's default or other prices are selected). Is there another method to use in this situation?
Here is the issue:
https://jsfiddle.net/tn5xtfss/
var base_price = 0;
function CalculatePrice() {
var base_cost = base_price;
$(".quote--price:checked").each(function() {
base_cost += $(this).data("price");
});
$("#final_price").text(base_cost);
}
CalculatePrice();
$(".quote--price").click(function() {
CalculatePrice();
});
Parse your number
base_cost += parseFloat($(this).data("price"));
demo
I am trying to create a simple jQuery calculator but it doesn't seem to be working as I hope it to be. Basically it should calculate automatically at 0 the price from the input boxes and then multiply when the +/- are clicked.
It doesn't seem to do anything or show any errors.
jQuery(document).ready(function(){
var qty = parseInt($('.qty').val());
var price = parseFloat($('#price').val());
$("#price").each(function(){
total += parseFloat(this.value);
});
http://jsfiddle.net/hktxyz5z/1/
I am not sure if I am over thinking, anyone got any ideas?
You need to give the variable declarations inside the click event:
var qty = parseInt($('.qty').val());
var price = parseFloat($('#price').val());
The reason is, you are statically setting the values to 0.00 at the first load. Every time you increment or decrement, the values do not change. It is set once and not set when it is changed. They don't dynamically change, after the click events are fired.
The solution is to put the above two lines inside the .click() functions.
jQuery(document).ready(function(){
$("#price").each(function(){
total += parseFloat(this.value);
});
// This button will increment the value
$('.qtyplus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
qty = parseInt($('.qty').val());
price = parseFloat($('#price').val());
$('#total').val((qty * price ? qty * price : 0).toFixed(2));
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
qty = parseInt($('.qty').val());
price = parseFloat($('#price').val());
$('#total').val((qty * price ? qty * price : 0).toFixed(2));
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
qty = parseInt($('.qty').val());
price = parseFloat($('#price').val());
$('#total').val(((qty * price > 0) ? qty * price : 0).toFixed(2));
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
qty = parseInt($('.qty').val());
price = parseFloat($('#price').val());
$('#total').val(((qty * price > 0) ? qty * price : 0).toFixed(2));
}
});
});
Working Fiddle: http://jsfiddle.net/txk2d85y/
jQuery provide a plugin which may help you : "jQuery-Calx"
watch its demostration here :
http://prototype.xsanisty.com/calx2/
I'm not sure why you have two price boxes, but I've updated the fiddle to have 1, since this causes some unusual behaviour.
However, the root of the problem is that you have declared qty and price on document.ready, but then are not updating them whenever the buttons are clicked. Here is a fiddle demonstrating one solution:
http://jsfiddle.net/hktxyz5z/2/
However, I feel like you could make the whole thing much shorter and cleaner, reducing repetition of code between the plus and minus buttons. Stay tuned for an update with a recommendation...
Update
Here is a refactored version:
http://jsfiddle.net/hktxyz5z/3/
The changes I've made are:
You don't need an input, since you are simple preventing the default action anyway. In that case it is better to use a <button>, which I have done.
Both quantity buttons now respond to the same event handler, which simple reads the adjustment attribute from the button and passes it to the adjustQty function.
The adjustQty function then calculates the new total, and updates the text boxes.
If I've missed something obvious regarding the purpose of the second price box, please let me know and I'll adjust my example.
Update 2:
I'm guessing that you want to add up both price values, then multiply by the quantity? If so, this amended example should do the trick:
http://jsfiddle.net/hktxyz5z/4/
The only real difference is that it calculates the total for both price boxes before it multiplies by the quantity.
Like written in the Title. I am trying to get the sum from some fields - this is working fine already. But I want to add a function that if the check box is checked before and I press the "Calculate" Button the sum should be divided / 2 automatically. I don't have the code I already have in the moment but if its needed I will upload later. But for now maybe its some easy thing and very general. Maybe someone can give some example already. kind regards
Since you did not provide any markup, you should do something like this, but adapted to your code:
var sum = calculateSum();
if ($("#checkbox").is(':checked')) sum = sum/2;
$('#calculateButton').on('click', function(){
// do summation and assign it to sum variable
var sum = sumCalculation();
if ($('#checkbox').is(':checked'))
{
sum = sum/2;
}
});
You may try:
$("#checkbox").change(function(){
if($(this).is(':checked')){
// do the division
}
});
Assuming your checkbox would have id="checkbox"
var chksum = document.getElementById('u r checkbox ID').checked;
if(chksum=="true")
{
sum=sum/2;
}
Try this. Note let the id of checkbox is #checkbox
var sum = 10;
$("#checkbox").change(function(){
if($(this).is(':checked')){
sum /=2;
}
alert(sum);
});
Question
I have a form that uses jQuery for magic. On that form is a button Add Account. That button appends fields Account and Amount and also another button Remove Account (which if you can guess, removes those two fields). This all works nicely...
On the same form there is another field Salary, which I would like to compare with the total of all the Amount fields. The problem is when I use jQuery's $.each() to iterate through the Amount fields it only recognizes those fields that were present in the DOM when the page loaded, and not the newly added fields.
How can I iterate through these appended Amount fields? (Or maybe there is a better to do this altogether?)
What I'm doing now:
$(document).ready(function(){
$('#form').on('keyup', '.amount', balanceAmountsWithSalary);
});
var balanceAmountsWithSalary = function(){
var salary = parseInt($('#salary').val(),10);
var total = 0;
$('#accounts .account').each(function(){
var amount = parseInt($(this).find('.amount').val(),10);
total += amount;
});
if (total === salary) {
$('#accounts .account').each(function(){
// Do some stuff to each input.amount located in div.account
});
} else {
$('#accounts .account').each(function(){
// Do some BAD stuff to each input.amount located in div.account
});
}
}
Thanks!
Answer
So it probably would've been more helpful to include the rest of my code at the outset as the problem was a simple error in the add account event. I mislabeled my container class adding an "s" to name of the appended items only. In any case thats for the comments! Posting an example on jsFiddle helped me find this error, so here is the thing in action in case you were wondering.
As HTML code and code of Dynamic adding inputs are not provided, I have edited an existing Fiddler to get total of dynamic added input field.
In this fiddler simple for loop is used to calculate total amount.
Here is a fiddler which might help you.
//button click get total
$('#GetTotal').click( function(event){
var tableID = "NewInvoiceTable";
GetTotalAmount(tableID);
return false;
});
//Get total
function GetTotalAmount(tableID)
{
var i = $('#' + tableID + ' tr').length;
alert("Total Rows -" + i);
var TotAmt = 0;
for(j=0;j<i;j++)
{
TotAmt += parseInt($('#TotalInline-' + j).val());
}
alert("Total Amount - " + TotAmt);
}
This may have been answered before, but I cannot find a solution that works.
I need to add the subtotal input boxes up and output them as a grandTotal. Sounds simple, and I thought it would be, but for some reason I cannot get it to function properly.
To save time I have created a jsFiddle - http://jsfiddle.net/wgrills/hKxgU/4/
Edit: Sorry to be poor at posting the question.
I missed out most of the items because I wanted to speed the jsfiddle up. I have updated the jsFiddle - http://jsfiddle.net/wgrills/hKxgU/7/.
If you click on the + or - buttons the subtotal changes, that is all good. But I can't get the #grandTotal input to update. The problem appears to be with the:
var grandTotal = 0;
$(".subtotal").each(function() {
$(this).css("border-color","#f00");
grandTotal += $(this).val.split("£")[1];
});
$("#grandTotal").val("£" + grandTotal);
alert(grandTotal);
part of the js. Note the css border change and the alert is just there for me to make sure the script is working.
The code is all early days, this is just a quick mock up.
You gave two problems, very easy to solve!
You are correct that the piece above that you posted is part of the problem. In particular the line:
grandTotal += $(this).val.split("£")[1];
You missed the () after val, so the code WOULD have broken here, because it doesn't know what .val. is.
Also, the code you posted was after a return false; this effectively tells the function is has finished, don't bother doing anything after that line.
However, as you need that section of code in both functions (clicks) its worth wrapping it in a function of its own:
function updateGrandTotal() {
var grandTotal = 0;
$(".subtotal").each(function() {
$(this).css("border-color", "#f00");
grandTotal += parseFloat($(this).val().split("£")[1]);
});
$("#grandTotal").val("£" + grandTotal);
alert(grandTotal);
}
And calling it just before you inform the function its finished:
updateGrandTotal();
return false;
See it partially working here
However, while this will work on the plus of an item, you have another problem, when you are minusing an item, and the box gets to zero, instead of setting £0.00 you set it to 0, hence when it try's to split on the "£" it can't. To combat this simply copy the bit where you turn your price value into a price from the plus function into the minus function:
Replace:
newprice = price * x;
$('#' + update).val(x);
$('#' + update + '_subtotal').val(newprice);
With the working version:
newprice = (price * x) / 100;
newprice = newprice.toFixed(2);
newprice = '£' + newprice;
$('#' + update).val(x);
$('#' + update + '_subtotal').val(newprice);
See it fully working here
Your problem is with the following line:
grandTotal += $(this).val.split("£")[1];
val is a function, not a property on the returned object. You want the following instead:
grandTotal += $(this).val().split("£")[1];
Also in your fiddle you have a return false; in the middle of your function, which lies above the code you're calling val incorrectly on. Remove that return as well.