我有产品列表,我想在选中其复选框时计算其价格,目前我的代码将计算所有复选框,包括未选中的复选框。
args[0]
JavaScript
<script>
$(document).ready(function () {
$(".bundlechecked").on('click', function () { //div checkbox
var pp = 0;
$(".thisPrice").each(function() { //input where price comes from
if(!isNaN(this.value) && this.value.length!=0)
{
pp += parseFloat(this.value);
}
});
console.log(pp);
});
});
</script>
Blade (View)
我评论了代码以更好地理解
有什么想法吗?
答案 0 :(得分:1)
尝试一下:
<script>
$(document).ready(function () {
$(".bundlechecked").on('click', function () { //div checkbox
var pp = 0;
$(".thisPrice").each(function() { //input where price comes from
var checkbox = $(this).parent("label").find("input[type=checkbox]");
if (checkbox.prop('checked') && !isNaN(this.value) && this.value.length!=0)
{
pp = +pp + +parseFloat($(this).val());
}
});
console.log(pp);
});
});
</script>
这是JSFiddle:https://jsfiddle.net/leonenco/8ojdesz6/26/
答案 1 :(得分:1)
尝试一下
onchange
事件更好
var price = 0;
const calculatePrice = function(e) {
let val = $(e).siblings().first().find('.caption .thisPrice').first().val();
if(!isNaN(val) && val.length != 0){
price += parseInt(val);
}
};
$(document).ready(function(){
$('.bundlechecked').on('change', function(e){
price = 0;
$('.bundlechecked:checked').each((i, e, s) => calculatePrice(e));
console.clear();
console.log('Total price =>', price);
});
});
label { display: block;}
label * { display: inline;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" class="bundlechecked">
<div class="product-thumb">
<div class="caption">
<h4>Product One - 10</h4>
<input type="hidden" class="thisPrice" value="10">
</div>
</div>
</label>
<label>
<input type="checkbox" class="bundlechecked">
<div class="product-thumb">
<div class="caption">
<h4>Product Two - 25</h4>
<input type="hidden" class="thisPrice" value="25">
</div>
</div>
</label>
<label>
<input type="checkbox" class="bundlechecked">
<div class="product-thumb">
<div class="caption">
<h4>Product Three - 12</h4>
<input type="hidden" class="thisPrice" value="12">
</div>
</div>
</label>
<label>
<input type="checkbox" class="bundlechecked">
<div class="product-thumb">
<div class="caption">
<h4>Product Four - 30</h4>
<input type="hidden" class="thisPrice" value="30">
</div>
</div>
</label>
<label>
<input type="checkbox" class="bundlechecked">
<div class="product-thumb">
<div class="caption">
<h4>Product Five - 15</h4>
<input type="hidden" class="thisPrice" value="15">
</div>
</div>
</label>
答案 2 :(得分:0)
尝试一下
$(document).ready(function () {
$("input[type='checkbox']").on('click', function () {
if($(this).is(':checked')) {
var getCurrentParent = $(this).parents('.bundlechecked').first();
var pp = [];
$(getCurrentParent).find(".thisPrice").each(function() { //input where price comes from
if(!isNaN(this.value) && this.value.length!=0)
{
pp.push(this.value);
}
});
console.log(pp);
}
});
});