Reputation: 169
I have this checkboxes
<input type="checkbox" class="calc" name="access[a]" value="1" />
<input type="checkbox" class="calc" name="access[b]" value="2" />
<input type="checkbox" class="calc" name="access[c]" value="3" />
<input type="checkbox" class="calc" name="access[d]" value="4" />
I need the following thing, i will explain it in an example: Let's say i have selected the first and the second checkbox then "ab"([access[a]+access[b]) and "3"(1+2) will be send.
EDIT1: You did not undertsand me.I want 2 things to be send, calculation of value and access[values].
Example: User selects third and fourth fields, 7(3+4) and cd ([access[c]+access[d]) will be send.
Upvotes: 0
Views: 110
Reputation: 236182
Yet another vanilla solution:
var res = [ ].reduce.call( document.querySelectorAll( 'input.calc:checked' ), function( a, b ) {
return a + (+b.value || 0);
}, 0);
Demo: http://jsfiddle.net/fsbTS/
Upvotes: 2
Reputation: 133453
You can simply loop through it
var added= 0;
$(".calc:checkbox:checked").each(function () {
added += +$(this).val();
});
Upvotes: 0
Reputation: 22425
Obligatory vanilla answer:
Grab the elements in an array by class (you can also use querySelectorAll(".calc")
(or [name*='access']
etc)
Loop the array of elements, check for the checked property, and add to the sum (making sure to parse the value as an Int to avoid NaN
issues)
var sum = 0;
var x = document.getElementsByClassName("calc");
for (var i=0; i<x.length; i++) {
if (x[i].checked) sum+= parseInt(x[i].value,10); //parse as int
}
Upvotes: 0