简体   繁体   中英

Multiple checkbox checked value

I have written the following code in JSFiddle to able so get the sum of combined values of the checkboxes.

Script

var inputs = document.getElementsByClassName('sum'),
        total  = document.getElementById('payment-total');

 for (var i=0; i < inputs.length; i++) {
        inputs[i].onchange = function() {
            var add = this.value * (this.checked ? 1 : -1);
            total.innerHTML = parseFloat(total.innerHTML) + add
        }
    }

Code

<input value="33" type="checkbox" class="sum" data-toggle="checkbox">
    <input value="50" type="checkbox" class="sum" data-toggle="checkbox">
        <input value="62" type="checkbox" class="sum" data-toggle="checkbox">
<span id="payment-total">0</span>

There it works perfect, when I implement this in my system there is no reslut or any error. The checkboxes in my system are genarated by an MySQL output.

Any suggestions what migh be wrong?

在此处输入图片说明

在此处输入图片说明

Your code is probably running before the elements are dynamically generated, so the event handlers are not being attached. Try delegating the event handlers using .on() method:

 $total = $('#payment-total'); $(document).on("click", ".sum", function() { var add = this.value * (this.checked ? 1 : -1); $total.text(function(i, value) { return parseFloat(value) + add; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input value="33" type="checkbox" class="sum" data-toggle="checkbox"> <input value="50" type="checkbox" class="sum" data-toggle="checkbox"> <input value="62" type="checkbox" class="sum" data-toggle="checkbox"> <span id="payment-total">0</span> 

I prefer to use pure javascript for your solution because you didn't use Jquery on your code. I think problem reason comes from Javascript eventListener . When you create a new element to your document, you should add its events.

In first code i create a checkbox but this is not work as others. link_1

<http://jsfiddle.net/3oweu107/1/>

However in second code i add event as other checkbox so payment-total value calculation done by new event. link_2

<http://jsfiddle.net/3oweu107/2/>

i hope this will help your problem :)

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