Reputation: 13
I am trying to display a dynamic price field, where the price gets updated based on multiple groups of selected radio buttons.
I got the calculation to work, but my problem occurs when the user changes the selection.
Here is my script:
jQuery(document).ready(function ($) {
var prijs = parseFloat($('.summary .price .amount').text().replace('€', '').replace('.', '').replace(',', '.'));
var total;
$('.product-addon-kleur input').change(function(){
var x = parseFloat($(this).closest('input:checked').attr('data-price'));
var total = prijs + x;
var total_decimal = '€'+total.toLocaleString('nl-NL', { minimumFractionDigits: 2 });
$('.summary .price .amount').text(total_decimal);
$('.product-addon input:not(.product-addon-kleur input)').change(function(){
var x2 = parseFloat($(this).closest('input:checked').attr('data-price'));
var new_total = total + x2;
var new_total_decimal = '€'+new_total.toLocaleString('nl-NL', { minimumFractionDigits: 2 });
$('.summary .price .amount').text(new_total_decimal);
});
});
});
As you can see there are multiple "radio button groups" that all need to be calculated in the totals.
But now, when a user changes his selection of the first radio buttons group (".product-addon-kleur input"), my script uses the starting price again (var total = prijs + x), excluding the value of the choice made in the second group (var x2).
How do I write my code to get calculations to work accurate?
Also in my version if "var total" isnt set yet by the first function, the second function doesnt work (var new_total = total + x2;). This means the user has to have a selection made in the first radio button group before the price will be updated..
It would be better if it could somehow fallback on "var prijs" if "var total" hasnt been set yet to calculate "var new_total = total + x2;"
Upvotes: 1
Views: 383
Reputation: 393
Write a single function that is triggered by both onChange events, which re-calculates everything each time any of the radios is changed.
function calc1() {
var prijs = parseFloat($('.summary .price .amount').text().replace('€', '').replace('.', '').replace(',', '.'));
var x = parseFloat($('.product-addon-kleur input').closest('input:checked').attr('data-price'));
var total = prijs + x;
var x2 = parseFloat($('.product-addon input:not(.product-addon-kleur input)').closest('input:checked').attr('data-price'));
var new_total = total + x2;
var new_total_decimal = '€'+new_total.toLocaleString('nl-NL', { minimumFractionDigits: 2 });
$('.summary .price .amount').text(new_total_decimal);
}
jQuery(document).ready(function ($) {
calc1();
$('.product-addon-kleur input').change(calc1);
$('.product-addon input:not(.product-addon-kleur input)').change(calc1);
});
Upvotes: 1