如何仅对单选按钮值求和一次?
我正在使用此代码对多个单选按钮的值求和:
$(document).ready(function(){
var total = 50000;
$("input[type=radio]").change(function(){
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
});
问题是,当用户单击组中的单选按钮,然后选择该组中的另一个单选按钮时,新值将添加到此,我只想添加其中一个值占总值的比例。
例如在这个组中:
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
当用户第一次选择第二个收音机时,5000将添加到总价中,但是如果他将其更改为第三个选项,则15000+5000将添加到总价中,我只想拥有其中一个!
I am using this code to sum values from multiple radio buttons :
$(document).ready(function(){
var total = 50000;
$("input[type=radio]").change(function(){
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
});
the problem is that when user click on a radio button in a group and then select another radio button in that group the new value will be add to this, i want to only add one of the values to the total value.
for example in this group :
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
when first time a user select seconed radio the 5000 will be add to total price, but if he change it to third option, 15000+5000 will be add to total, i want to have only one of them !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我看来,问题似乎是
total
var 被声明超出了change
回调的范围。这将导致change
回调的闭包包含total
变量,因此它的值将在后续change
调用中保留。如果在此回调中声明
total
,则应该没问题:The problem seems, to me, that the
total
var is declared out of the scope of thechange
callback. This will cause the closure of thechange
callback to contain thetotal
variable, so it's value will be persisted across subsequentchange
calls.If declare the
total
within this callback, you should be fine:我最近写了一个简单的例子来演示这一点(尽管我没有使用 jQuery)。
只需存储您添加的值,然后从总数中减去它,然后再添加新值。
I wrote a simple example demonstrating this recently (although I did it without using jQuery).
Just store the value you add, and then subtract it from the total before adding a new one.