简体   繁体   English

当html id是php变量时,如何在选中复选框时添加并在Javascript中未选中时扣除

[英]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.

相关问题 取消选中/选中复选框时,javascript在div中添加/删除文本 - javascript add/remove text in div when checkbox is unchecked/checked 选中/取消选中复选框时更改变量值 - Change variable value when checkbox is checked/unchecked 选中复选框后向JavaScript变量添加值 - Add value to JavaScript variable when checkbox is checked 如何将onchange属性添加到JavaScript生成的复选框,该复选框在选中/未选中时会触发? - How do I add an onchange attribute to a JavaScript generated checkbox that fires when checked/unchecked? 如何在选中复选框时隐藏内容并在未选中复选框时显示? - How to hide content when checkbox is checked and show when checkbox is unchecked? 选中复选框时的Javascript,将复选框ID添加到数组中 - Javascript when checkbox is checked, add checkbox ID to an array 当在角度中选中其他复选框时如何取消选中复选框 - how to make checkbox unchecked when other checkbox is checked in angular 如何在未选中复选框时显示Javascript确认框,然后如果用户选择取消,请选中复选框? - How to show Javascript confirm box when checkbox is unchecked and then if user selects cancel, leave the checkbox checked? 选中和取消选中时,将复选框值添加到数组中/从数组中删除复选框值(jQuery) - Add/remove checkbox values to/from array when checked and unchecked (jQuery) (Javascript / Wordpress)选中/取消选中复选框时显示不同的内容 - (Javascript/Wordpress) Show different content when checkbox is checked/unchecked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM