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
Related
$(document).ready(function() {
$('#clone').click(function() {
var target = $(this).closest('.groupcontainer');
target.clone(true, true).insertAfter(target);
});
$('.input').on('input',function(){
$(this).parent().children('.grouptotal').val($(this).val() *
$(this).parent().children('.input2').val());
$('.grouptotal').change();
});
$('.input2').on('input', function(){
$(this).parent().children('.grouptotal').val($(this).val() *
$(this).parent().children('.input').val());
$('.grouptotal').change();
});
$('.input2').dblclick(function(){
$(this).parent().children('.input2').autoNumeric('init', {aSign: "$ "});
});
$('.grouptotal').dblclick(function(){
$(this).parent().children('.grouptotal').autoNumeric('init', {aSign: "$ "});
});
$('#subtotal').dblclick(function(){
$(this).parent().children('#subtotal').autoNumeric('init', {aSign: "$ "});
});
$('.reset').click(function(){
$('.behindgroup').parent().children().find('input, textarea').val('');
});
});
$(document).on('change', '.grouptotal', function(){
var sum = 0;
$('.grouptotal').each(function(){
sum += +$(this).val();
});
$('#subtotal').val(sum);
});
Here's the Fiddle.
I have a function that does quantity * system = grouptotal.
My issue now is this. I have a plugin (autoNumeric) that will convert .grouptotal to USD$. However, when I double click it to convert, my #subtotal will change from a number to NaN. I've tried putting parseInt in every place I can think of, but it always reverts to NaN after the plugin is run. Prior to running the plugin, the #subtotal is fine, but they are not a dollar amount like I need.
I've changed sum += +$(this).val(); to sum += +parseInt($(this).val()) || 0; but it just ends up returning 0 in #subtotal.
How do I get #subtotal to pull just the number from .grouptotal after I've run my plugin to convert to $USD?
I hope this makes sense..
Using JavaScript, you could take advantage of regular expressions by doing something like this:
'$45.00'.match(/\d+/)[0]
Being '$45.00' your subtotal.
This was found here
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);
}
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!
I have multiple dropdown lists calculating a total price at the end, it works great apart from a few issues.
Firstly, I would like to add further prices to it, so it should read:
Total : £20.97
V.A.T : £4.19
Total Amount : £25.16
I'm sure this is simple but i cannot think how?
Secondly - It only works on a single selection drop down lists, if i want to select multiple options in one list, it will only calculate one
Here's the code i use to calculate the price:
$(function(){
$(".calculate").on("change", function(){
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
$('#total').text('£' + total.toFixed(2));
});
});//]]>
Thirdly, there are about 8 dropdown lists but i want the last one to discount the total price instead of adding to it, the code above takes the price from option value of each selection and so will the discount amount (In the discount column in the database, it's written as 10%.
So basically, after 7 lists i should have a total of i.e. £20.97 then once the last list is selected, it should replace the price with a discount amount i.e. (-10%) £18.87
I'm so close to finishing this but i can't get over the last hurdle.
Thanks
When a SELECT allows multiple selections the jQuery val() function returns an array of values. So your code needs to detect if val() returns and array and if so loop the array and add all those items. Here is one way:
$('.calculate').each(function() {
var currentValue = $(this).val();
if (currentValue.length != undefined) {
for (var i = 0; i < currentValue.length; i++) {
if (currentValue[i] != 0) {
total += parseFloat(currentValue[i]);
}
}
}
else if(currentValue != 0) {
total += parseFloat(currentValue);
}
});
That should take care of multiple select options. For the discount, just get the value of your final SELECT and apply your discount:
var discount = parseFloat($('.discount').val()) / 100;
total = total - (total * discount);
Is the Javascript pulling the values from the DDL from the Database or hard-coded into the form?
the computation for the % is 20.97 *0.10. Since the 10% is hard-coded this should work for the final drop down list.
Also, other than adding values to the form, and the computation for percentage, I'm not sure where the problem is, maybe some more information would be of value...