我遇到的问题是,我为一项服务提供了4个radiobuttons,当用户选择任何单选按钮时,使用javascript .change()函数将其值添加到total_sum。但问题是它不断增加虚假价值。就像你一次选择两个无线电盒一样。然后它会添加错误值
jQuery("input:radio").change(function() {
var total = parseInt(jQuery('#total_sum').val());
var ischecked= jQuery(this).is(':checked');
var unchecked = jQuery(this).is(':unchecked');
var price = parseInt(jQuery(this).val());
var newprice = total;
var sum = 0;
if(ischecked){
sum = total + Number(price);
jQuery('#total_sum').val(sum);
}
else if(unchecked){}
});
var total = parseInt(jQuery('#total_sum').val());
jQuery('#sqfootage').bind('change', function () {
var sqfootage = jQuery('#sqfootage').val();
var sqfootage_val = 0;
var sum = 0;
if(sqfootage >= 1 && sqfootage <= 1500)
{
sqfootage_val = 10;
}
else if(sqfootage >= 1501 && sqfootage <= 1800)
{
sqfootage_val = 15;
}
else if(sqfootage >= 1801 && sqfootage <= 2100)
{
sqfootage_val = 20;
}
else if(sqfootage >= 2101 && sqfootage <= 2400)
{
sqfootage_val = 25;
}
else if(sqfootage >= 2401 && sqfootage <= 2700)
{
sqfootage_val = 30;
}
else if(sqfootage >= 2701 && sqfootage <= 3000)
{
sqfootage_val = 35;
}
else if(sqfootage >= 3001 && sqfootage <= 3300)
{
sqfootage_val = 40;
}
else if(sqfootage > 3300)
{
sqfootage_val = 40;
}
sum = total + Number(sqfootage_val);
jQuery('#total_sum').val(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quest fl">
<legend>What is the total square footage?</legend>
<div class="one_col">
<input name="sqfootage" id="sqfootage" min="1" type="number" value="" placeholder="SqFootage:">
</div>
</div>
<div class="quest fl">
<legend>Services</legend>
<div class="one_col">
<label><input name="service1" value="10" vt="Standard (one time)" type="radio" i="0">1</label>
</div>
<div class="one_col">
<label><input name="service2" value="20" vt="Standard (one time)" type="radio" i="0">2</label>
</div>
<div class="one_col">
<label><input name="service3" value="25" vt="Standard (one time)" type="radio" i="0">3</label>
</div>
<div class="one_col">
<label><input name="service4" value="30" vt="Standard (one time)" type="radio" i="0">4</label>
</div>
</div>
<input id="total_sum" name="total_sum" class="medium" type="text" value="89">
答案 0 :(得分:1)
您的代码有错误。 jQuery不包含:unchecked selector。相反,您需要反转:checked
选择器。所以改变
var unchecked = jQuery(this).is(':unchecked');
到var unchecked = jQuery(this).not(':checked');
解决问题。不确定为什么你使用无线电而不是复选框。
答案 1 :(得分:1)
没有jQuery伪选择器':未选中'
你想要这一行:
var unchecked = jQuery(this).not(':checked');
我在jsFiddle中运行它,它在修复此错误后起作用。