Javascript 如何在jquery中使用复选框来获取打印值?
单击复选框时,我希望将价格值添加到#totalPrices id元素中,但我的代码不起作用 下面是一张图片,向您展示它的外观:Javascript 如何在jquery中使用复选框来获取打印值?,javascript,php,jquery,Javascript,Php,Jquery,单击复选框时,我希望将价格值添加到#totalPrices id元素中,但我的代码不起作用 下面是一张图片,向您展示它的外观: .val()方法返回一个字符串,因此您必须解析返回的值,然后才能执行算术运算,还需要通过选中的复选框循环计算当前值的总数,这样您就可以使用each()如下所示: var countChecked=function(){ var结果=0; $(“输入[类型=复选框]:选中”)。每个(函数(){ result+=parseInt($(this.val()); }) $(
.val()
方法返回一个字符串,因此您必须解析返回的值,然后才能执行算术运算,还需要通过选中的复选框循环计算当前值的总数,这样您就可以使用each()
如下所示:
var countChecked=function(){
var结果=0;
$(“输入[类型=复选框]:选中”)。每个(函数(){
result+=parseInt($(this.val());
})
$(“#总价”)。文本(结果);
};
countChecked();
$(“输入[类型=复选框]”)。单击(“单击”,计数已选中)代码>
Ajoutez des servicesávotre réservation:
服务
10欧元
服务
20欧元
保养大奖赛:X€
服务大奖:X€
总计:X€
此逻辑的选择器太宽。并且不处理取消勾选复选框。非常感谢您抽出时间。学习很多!
<form action="addServicesRequest.php" method="POST">
<div class="container form-control">
<h5>Ajoutez des services à votre réservation :</h5>
<?php while($services = $getServices->fetch()){ ?>
<div class="text-center">
<input type="checkbox" name="service" value="<?=$services['price']?>">
<label><?= $services['service']; ?></label>
<strong class="priceOfService"><?= $services['price']; ?>€</strong><br>
</div>
<hr>
<?php } ?>
<div>
<p>Prix de la réservation : <strong>X€</strong></p>
<p>Prix des services : <strong id="priceServices">X€</strong></p>
<h4>Total : <strong id="totalPrices">X€</strong></h4>
<input type="submit" value="Valider" class="btn btn-dark btn-sm container">
</div>
</div>
</form>
var result = 0;
var countChecked = function() {
var n = $( "input:checked" ).val();
$( "#totalPrices" ).text(result = result + n);
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
function countChecked () {
// select all the checked inputs (this takes care of unselecting a checkbox too)
// convert all their values to numbers
// reduce their values to a single total
var total = 0 + $( "input:checked" )
.map( function () { return parseInt( this.value ); } )
.get().reduce( function ( total, value ) { return total + value; }, 0 );
// update the total on the page
$( "#totalPrices" ).text( total );
}
$( "input[type=checkbox]" ).on( "click", countChecked );
countChecked();