[英]How to add when a checkbox is checked and deduct when unchecked in Javascript when html id is a php variable
I am trying to total a particular column amounts from a php array when a checkbox is checked and deduct from the total when it is unchecked.我试图在选中复选框时从 php 数组中汇总特定列的金额,并在未选中时从总数中扣除。 I can get it to add when checked but can not get it to reduce from the total when unchecked.
我可以在选中时添加它,但在未选中时无法从总数中减少它。 In fact the code below adds every time the checkbox is checked or unchecked.
事实上,每次选中或取消选中复选框时,下面的代码都会添加。
Please help请帮忙
<html>
<body>
<?php
$testArray = [100000,200000,300000,144444,154444,16444,174444,18444];
?>
<div>
<?php for($i=0;$i<count($testArray);$i++) { ?>
<input type="checkbox" id = <?php echo $i ?> onclick="myFunction(<?php echo $testArray[$i] ?>)" value="<?php echo $testArray[$i] ?>" ><?php echo $testArray[$i] ?> <br/>
<?php } ?>
</div>
<table>
<tr style = "display: none;" >
<td></td>
<td id = 'balance'> 0 </td>
</tr>
<tr>
<td> Total : </td>
<td id = 'balance1'> 0 </td>
</tr>
</table>
<script>
// cumulative = 2
function myFunction(x){
balance = document.getElementById('balance').textContent;
total = parseInt(balance)
total = total + x
document.getElementById('balance').textContent = total
// display with number formated
total = total.toLocaleString("en-US");
document.getElementById('balance1').textContent = total
}
</script>
</body>
</html>
<?php for($i=0;$i<count($testArray);$i++) { ?>
<script>
if (document.getElementById("<?php echo $i ?>").checked === true) total += x;
</script>
<?php } ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.