我的表中有幾個復選框(未指定編號),并2000為每個復選框設定了一個值。我希望將每個選中的復選框乘以2000,如果未選中2000,則從總金額中扣除?
例如,如果選中了 3 個復選框,則數字 3 乘以2000, 3 * 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>
uj5u.com熱心網友回復:
您只需使用:checked偽選擇器即可獲得選中的復選框
const multiplier = 2000;
function getTotalPrice(){
const checkedCount = $('.check-horse:checked').length;
return checkedCount * multiplier;
}
$(document).on('change','.check-horse', e=> $('.totalprice').text(getTotalPrice());
它應該按預期作業。
uj5u.com熱心網友回復:
詳細資訊在下面的示例中進行了注釋。請注意,每個復選框的值已分配為 2000。此外<span>,使用 an而不是 a <output>——它是一個行內標簽,可以包含像 a 這樣的文本<span>,但與<span>an不同的是<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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437463.html
標籤:jQuery
