当我单击一个复选框时,我希望将价格值添加到#totalPrices id元素中,但是我的代码不起作用。
这是一张图片,向您展示它的外观:
<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>
这是jquery:
var result = 0;
var countChecked = function() {
var n = $( "input:checked" ).val();
$( "#totalPrices" ).text(result = result + n);
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
答案 0 :(得分:3)
.val()
方法返回一个字符串,因此您必须解析返回的值,然后才能执行算术运算,还需要遍历选中的复选框来计算当前复选框的总数,因此可以使用{ {1}}像:
each()
var countChecked = function() {
var result = 0;
$("input[type=checkbox]:checked").each(function() {
result += parseInt($(this).val());
})
$("#totalPrices").text(result);
};
countChecked();
$("input[type=checkbox]").on("click", countChecked);
答案 1 :(得分:1)
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();