2 回答
TA贡献1825条经验 获得超4个赞
您只需在循环内定义 getItemPrice 即可,否则您只需为单击的项目计算一次,而不是为每个项目执行一次。
$(function() {
$('.dealprice').on('input', function(){
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
<table class="tg">
<thead>
<tr>
<th class="tg-qh0q">Item</th>
<th class="tg-qh0q">Price</th>
<th class="tg-qh0q">Deal</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-0lax">Book</td>
<td class="tg-0lax">$ 10 <input type="hidden" name="itemprice" value="10"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][0]"></td>
</tr>
<tr>
<td class="tg-0lax">Pencil</td>
<td class="tg-0lax">$ 5 <input type="hidden" name="itemprice" value="5"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][1]"></td>
</tr>
<tr>
<td class="tg-0lax">Pen</td>
<td class="tg-0lax">$ 8 <input type="hidden" name="itemprice" value="8"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][2]"></td>
</tr>
<tr>
<td class="tg-amwm" colspan="2">Total</td>
<td class="tg-0lax"><span id="totalDeal">0</span></td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TA贡献1807条经验 获得超9个赞
您必须将getItemPrice其放入检查的函数内部。请检查以下代码:
$(function() {
$('.dealprice').on('input', function(){
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
另请检查此 repl https://repl.it/repls/LavenderAgonizingRoot
- 2 回答
- 0 关注
- 111 浏览
添加回答
举报