Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum value of checked changed checkbox jquery?

I have a table, each checkbox contains a value, and I want to sum value of the checkbox.

Example:

Candy and Water is checked : count = 2 , Candy, food and water is checked : count = 5 , checkbox is unchecked : count = 0 . I think i must two event , event of each checkbox (.checkbox1) and event of checkbox (.check_all).

Javascript

      var count = 0;
            $(".checkbox1").change(function() {
                var table_abc = document.getElementsByClassName("checkbox1");
                for (var i = 0; table_abc[i]; ++i) {
                    if (table_abc[i].checked) {
                        count += table_abc[i].value;
                    }
                }
           });

alert(count);

HTML

<table id="div_table">
    <thead>
        <tr>
            <th><input type="checkbox" class="check_all" id="chk_all" /></th>
            <th>Check All</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" class="checkbox1" id="candy" value="2" /></td>
            <td>Candy</td>
        </tr>
        <tr>
            <td><input type="checkbox" class="checkbox1" id="food" value="3" /></td>
            <td>Food</td>
        </tr>
        <tr>
            <td><input type="checkbox" class="checkbox1" id="water" value="0" /></td>
            <td>Water</td>
        </tr>
    </tbody>
</table>

But it seems not working. Can you tell me how to wrong?

like image 747
Brian Crist Avatar asked Jan 07 '23 18:01

Brian Crist


2 Answers

here is your script, a little bit improved i'm using here the jquery .prop() method to get the checked property of each element, and instead of performing concatenation directly with the value of count you have to use Number(number) or parseInt(number,base) in order to tell js engine, hey i want it to be an arithmetic operation and not a concatenation

here is your snippet of code improved :

$(document).ready(function(){

 var count;

            $(".checkbox1").change(function() {
                count = 0;

                var table_abc = $('.checkbox1');

                for (var i = 0; i < table_abc.length ; ++i) {


                    if ($(table_abc[i]).prop('checked')) {
                        count += parseInt($(table_abc[i]).val(),10);
                    }
                }

            console.log(count);

           });



});

we are logging to the screen the value of count each time a checkbox(with class checkbox1) state is changed

like image 57
ismnoiet Avatar answered Jan 19 '23 20:01

ismnoiet


First I moved declaration of variable count inside the change function to avoid invalid value in repeating the checked-unchecked

Then you should cast the value of checkbox to a numeric so your summation gives correct values

check this fiddle, it works

like image 27
Mohamed Badr Avatar answered Jan 19 '23 19:01

Mohamed Badr