我从我的数据库中检索了具有相应item_name和值的复选框,这些复选框恰好正确显示,但是在选中/选中时会自动添加/减去这些值。但是,我想保存选中的复选框item_names以及复选框中值的总和。我无法完成此操作,因为value选项包含数字数据,该数据应该是复选框item_name;到目前为止我所拥有的一切。
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 0;
for (i=0;i<document.listForm.sel_car.length;i++) {
if (document.listForm.sel_car[i].checked) {
sum = sum + parseInt(document.listForm.sel_ca[i].value);
}
}
document.listForm.total.value = sum;
}
</script>
HTML / PHP代码段
<h4>Available Cars | Click on desired car(Multiple Selections enabled) | Total Price: <input type="text" size="2" name="total" value="0"/></h4>
<div class="form-group">
<?php
$stmt = $DB_con->prepare('SELECT * FROM cars ORDER BY car_id DESC');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<div class="col-md-3"><label class="btn btn-primary">
<img src="user_images/<?php echo $row['userPic']; ?>" alt="..." class="img-thumbnail img-check"><input type="checkbox" name="sel_car[]" id="item4" value="<?php echo $row['car_price']; ?>" class="hidden" autocomplete="off" onchange="checkTotal()"/>
<h5><?php echo $row['se_car_model']; ?> | UGX <?php echo $row['car_price']; ?>/=</h5>
</label></div>
<?php
}
}
?>
答案 0 :(得分:0)
您还应该检索ID以及项目名称和值,并将ID分配给复选框。
在表单中添加隐藏字段
<input type="hidden" name="itemsArr" id="itemsArr" value="">
复选框强>
<input onclick="checkTotal(this)" type="checkbox" id="itemId" name="ItemName" value="ItemPrice">
Div显示总金额
<div id="totalDiv"></div>
<强>脚本强>
<script type="text/javascript">
var arr = [];
var total = 0;
function checkTotal($this)
{
var varId= $this.id;
if ($($this).is(":checked")) {
arr.push(varId);
}
else
{
arr.splice( $.inArray(varId,arr) ,1 );
}
$("#itemsArr").val(arr);
// get the price of the item from the controller by passing id to controller
$.ajax({
type: 'POST',
url: BASE_URL+"controllerName/methodName",
data: {'id':varId},
success: function (data) {
data = JSON.parse(data);
total += data.price;
$("#totalDiv").html(total);
}
});
}
在对表单进行汇总时,您将获得隐藏值,然后将其存储在数据库中
如果要从数据库中检索值,可以使用explode函数获取字段并将该字符串转换为数组,然后执行其他任务。