如何使用jQuery创建基于复选框的计算函数



我的表中有几个复选框(未指定数字(,并为每个复选框设置值2000。我希望选中的每个复选框乘以2000,如果未选中2000,则从总额中扣除?

例如,如果选中3个复选框,则数字3乘以20003 * 2000。如果从这个数字中取消选中,它的值将从总数中扣除?

并在span中显示总值?

<table class="table">
<thead>
<tr>             
<th>
choose
</th>
</tr>
</thead>
<tbody>
@foreach (var item in listitem)
{
<tr>                                                 

<td>
<input class="check-horse mr-2" type="checkbox" autocomplete="off" />
</td>
</tr>
}
</tbody>
total price :<span class="text-success totalprice"></span>

只需使用:checked伪选择器即可获得选中的复选框

const multiplier = 2000;
function getTotalPrice(){
const checkedCount = $('.check-horse:checked').length;
return checkedCount * multiplier;
}
$(document).on('change','.check-horse', e=> $('.totalprice').text(getTotalPrice());

它应该按预期工作。

下面的示例对详细信息进行了注释。请注意,每个复选框的值已指定为2000。此外,使用<output>代替<span>——它是一个内联标签,可以像<span>一样包含文本,但与<span>不同的是,<output>也可以像表单控件一样具有value(例如<input><select>等(。

/*
Whenever the user changes the state of any checkbox the event
handler chkSum(e) is invoked
*/
$(':checkbox').on('change', chkSum);
// Event handler is a function that listens for events
function chkSum(e) {
// Define a 0 value in outer scope
let total = 0;
// On each checkbox that's CHECKED...
$(':checkbox:checked').each(function() {
// Add the checkbox value (converted into a real number) to total
total += Number($(this).val());
});
/* 
After iterations display total value 
output.total can also use .val()
*/
$('.total').text(total);
};
<fieldset>
<output class='total'>0</output><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
</fieldset>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

最新更新