Reputation: 1711
I have a form where people can build up an order choosing different options, i.e. they choose a base price first and then add to that. The radio buttons are hidden and the labels styled to be the clickable area instead.
The requirements include being able to deselect the radio button (i.e. you can reset your choice back to null if you want) which I've got working OK in the code below.
I also have to write the values to other elements on the page. That's working OK too.
What's not working right is adding the values of different groups of radio buttons together.
$('.order-option + label').click(function(e) {
var radio = $(this).attr('for');
radio = $('#' +radio );
var spec_price = 0;
var env_price = 0;
switch($(radio).attr('name')) {
case 'specifications':
spec_price = parseInt(radio.val());
break;
case 'envelopes':
env_price = parseInt(radio.val());
break;
}
var total_price = +spec_price + env_price;
var desc = radio.data('title');
if(radio.is(':checked')) {
e.preventDefault();
radio.removeAttr('checked');
}
$('.order-preview-total').html('$'+total_price+' (inc gst)');
$('#order-preview-total').val('$'+total_price+' (inc gst)');
$('.order-preview-content').html(desc);
$('#order-preview-content').val(desc);
});
When I click on the second row of radio buttons, it just overwrites the price, rather than adding to it.
It's also not resetting the total to 0 if all the radio buttons are deselected again.
The elements with classnames (e.g. .order-preview-total) are the ones displaying the info, the ones with IDs are hidden form elements for passing the data to another form.
As requested, I've created a JSFiddle. If you click any of the buttons in the second row, the value should be added to the ones you've already selected in the first row. If you click on an option you've already chosen again, i.e. to deselect it, that value should be subtracted again.
Upvotes: 2
Views: 223
Reputation: 1284
Well, I guess in case of total price you need to declare your total_price variable outside the function and set is equal to 0, otherwise it will overwrite it every time you click radio button.
in terms of subtracting value if button is checked. It's hard to say without an HTML, but seems to me that you need to modify your if statement as follows:
if(radio.is(':checked')) {
e.preventDefault();
var subtract = parseInt(this.val());
total_price = total_price - subtract;
radio.removeAttr('checked');
}
Upvotes: 1