已更新
我使用while循环显示复选框,复选框的值是金额。现在,当通过ajax函数检查复选框时,代码可以显示总值。在表单提交期间,如何获取已检查值的$ ID?由于复选框的名称不是数组,我不知道如何以其他方式做。请帮助:'(提前致谢!
PHP:
<table>
<form name="listForm">
<?php
while($row=mysql_fetch_assoc($result)){
$ID = $row['ID'];
$amount = $row['amount'];
?>
<tr>
<td><input type="checkbox" name="payID" data-payment-id="<?php echo $ID;?>" value="<?php echo $amount;?>" onclick="calculate();"></td>
</tr>
<?php
}?>
</table>
</form>
javascript:
function calculate(){
document.listForm.payID.value = '';
var sum = 0;
var count = 0;
for (i=0;i< document.listForm.payID.length ; i++) {
if (document.listForm.payID[i].checked) {
sum = sum + parseInt(document.listForm.payID[i].value);
count = count + 1;
}
}
document.getElementById('payable').innerHTML = "Total record chosen= "+ count +"<br>Total amount= " + sum + "<br>";
}
答案 0 :(得分:0)
我现在更新了。在你的PHP代码中修改这一行:
<input type="checkbox" name="payID" data-payment-id="<?php echo $ID;?>" id="payment_id[]" onClick="calculate()" value="<?php echo $amount;?>" >
你的Javascript功能:
function calculate(){
var sum = 0;
var count = 0;
var a1=document.listForm['payment_id[]'];
for(i=0;i<a1.length;i++){
if (a1[i].checked){
sum += parseInt(a1[i].value);
count = count + 1;
}
}
document.getElementById('payable').innerHTML = "Total record chosen= "+ count +"<br>Total amount= " + sum + "<br>";
}
答案 1 :(得分:0)
您需要获取&#34; data-payment-id&#34;来自单击的复选框的属性。我将它们存储在一个数组中,然后json将其字符串化以便以您的形式发送。
<强>使用Javascript:强>
function calculate(){
document.listForm.payID.value = '';
var sum = 0;
var count = 0;
var idList = [];
for (i=0;i< document.listForm.payID.length ; i++) {
if (document.listForm.payID[i].checked) {
sum = sum + parseInt(document.listForm.payID[i].value);
count = count + 1;
idList.push(document.listForm.payID[i].getAttribute('data-payment-id'));
}
}
document.getElementById('sum').value = sum;
document.getElementById('count').value = count;
document.getElementById('idList').value = JSON.stringify(idList);
return true;
}
然后对于你的表单,更新它以获得隐藏的输入和onsubmit函数 - 这是我用于测试的内容:
HTML表格:
<form name="listForm" action="aoeu.php" method="post" onsubmit="calculate()">
<input type='checkbox' name="payID" value='1' data-payment-id='aaa'> 1<br>
<input type='checkbox' name="payID" value='2' data-payment-id='bbb'> 2<br>
<input type='checkbox' name="payID" value='3' data-payment-id='ccc'> 3<br>
<input type='hidden' id='sum' name='sum'>
<input type='hidden' id='count' name='count'>
<input type='hidden' id='idList' name='idList'>
<button type='submit'>Submit</button>
</form>
然后只需确保json_decode()
您在PHP帖子中获得的idList。