I have four variables which begin on page load like this (NOTE: all together add up to 100)...
a=60;
b=20;
c=10;
d=10;
I have three checkboxes like this..
<label for="b">B</label>
<input type="checkbox" id="b" name="b" value="" checked="checked" >
<label for="c">C</label>
<input type="checkbox" id="c" name="c" value="" checked="checked" >
<label for="d">D</label>
<input type="checkbox" id="d" name="d" value="" checked="checked" >
As you can see, all three checkboxes are checked by default. I want to change the variables from above based on checking/unchecking any of these three boxes. Essentially, unchecking a checkbox is turning OFF that variable and making it's value 0. In other words:
var b will be either 20 (when it's checkbox is checked) or 0 if it's unchecked
var c will be either 10 (when it's checkbox is checked) or 0 if it's unchecked
var d will be either 10 (when it's checkbox is checked) or 0 if it's unchecked
And when any of those are unchecked, I want to add their value to var a because I want all 4 variables to always add up to 100
So for example, if all three checkboxes remain checked, var a remains 60. If checkbox B is unchecked and C/D remain checked, var a becomes 80 (original 60 plus 20 from "turned off" var b)
My thought was to do something like this...
$(function() {
$("input[type='checkbox']").change(function() {
if(document.getElementById('b').checked) {
var a = a-20;
var b = 20;
} else {
var a = a+20;
var b = 0;
}
//and do this for all three checkboxes
})
})
But then I realize that if I look at EACH box every time ANY of them are changed, then I would unnecessarily subtract values from var a for 2 of them, since they are checked by default.
Regardless, I'm sure having a block of code for each block is probably an inefficient way to handle this. Anybody have any direction for me on possibly condensing the code, specifically only adding/subtracting value when specific checkboxes are CHANGED (since simply seeing if they are checked would cause issues since they are all checked by default)
For example in the code above, if checkbox D was unchecked and triggered the function, it would look at checkbox B and see that it's checked and subtract 20 from a, but it shouldn't because B hasn't changed at all yet.
Sorry for rambling, hope this makes some sense to somebody.