Reputation: 420
I have a long list of variables that depending on what is selected change the total price. I am trying to take an existing variable, and add the value of a radio button to it, but only if the radio button is selected. I have this working, but when I change the radio button selected it continues adding to the existing number. I need to be able to change which radio button is selected, and it remove the previously added number and add the value of the newly selected one. Is this possible, or am I going to have to rethink this one?
$('.pestOptions').click(function () {
var selection = $('.pestOptions:checked').val();
var programCost = $('.programCostPestControl').text();
var pestTotalFinal = parseFloat(selection) + parseFloat(programCost);
if(isNaN(pestTotalFinal)) {
$('.programCost').html('Call For Pricing');
}
$('.programCostPestControl').text(pestTotalFinal.toFixed(2));
});
Upvotes: 0
Views: 80
Reputation: 14927
You just need to change where things are set, and a couple other things. Here's a working sample:
// Set this value outside of the radio button change handler,
// so its more like in the global scope
var programCost = $('.programCostPestControl').val();
// set the handler for the radio button change event
$('input[name="rbg"]').change(function () {
var checkedVal = $('input[name="rbg"]:checked').val();
// `programCost` is already set outside of this function,
// so it doesn't change -- only gets added to
var pestTotalFinal = parseFloat(checkedVal) + parseFloat(programCost);
if(isNaN(pestTotalFinal)) {
$('.programCost').html('Call For Pricing');
}
$('.programCostPestControl').val(pestTotalFinal.toFixed(2));
});
(For this HTML)
<label>Add 2 <input class="pestOptions" type="radio" name="rbg" value="2"/></label><br/>
<label>Add 4 <input class="pestOptions" type="radio" name="rbg" value="4"/></label><br/>
<input class="programCostPestControl" type="text" value="12"/>
Upvotes: 1