我有一长串变量,根据所选内容改变总价。我正在尝试获取现有变量,并向其添加单选按钮的值,但仅在选中单选按钮时。我有这个工作,但当我更改选定的单选按钮时,它继续添加到现有的数字。我需要能够更改选择的单选按钮,并删除以前添加的数字并添加新选择的数字的值。这可能,或者我将不得不重新考虑这一个?
$('.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));
});
答案 0 :(得分:1)
您只需要更改设置的位置以及其他一些内容。这是一个工作样本:
// 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));
});
(对于此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"/>