简体   繁体   中英

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. 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 } ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM