【发布时间】:2017-01-06 09:04:29
【问题描述】:
我有两个功能。一个从checkboxes 添加值,另一个从radioboxes 添加值到var tot。
问题是radiobox 只对var tot 增加值,但在未选中时不会减去。
在我确定var tot 的范围之前,我没有遇到这个问题,但必须这样做,以便两个函数都可以访问它。这是一个解决问题的代码示例:
$(':checkbox:checked').prop('checked', false);
$('input[type="radio"]:checked').prop('checked', false);
$(document).ready(function() {
var tot = 0;
$('#usertotal').text('0 SEK')
$('input:checkbox').change(function() {
if (!$(this).is(':checked')) {
tot -= parseInt($(this).val());
} else {
tot += parseInt($(this).val());
}
$('#usertotal').text(tot + ' SEK')
});
$('input[type="radio"]').change(function() {
if ($(this).is(':checked')) {
tot += parseInt($(this).val());
} else if (!$(this).is(':checked')) {
tot -= parseInt($(this).val());
}
$('#usertotal').text(tot + ' SEK')
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<input type="radio" name="radioName" value="160 Yes">till 20
<input type="radio" name="radioName" class="someclass" value="5 Yes"> 20
<input type="checkbox" name="" value="29 Yes">BV
<div class="col-lg-4 col-mg-3 col-sm-12 col-xs-12 calculation-window">
Totalt: <span id="usertotal"></span>
</div>
【问题讨论】:
-
这已在另一个问题中讨论过。 The radio button "change" event only fires when activated, not when deactivated.您可能会发现在每个 onchange 事件中从头开始重复计算会更容易。
标签: javascript jquery