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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With