[Javascript] Adding checkbox values
Hassan Schroeder
hassan at webtuitive.com
Sat Feb 14 14:44:46 CST 2004
Alan Easton wrote:
> I am trying something which I think is simple. I have a form with 9
> checkboxes and a text box. Each checkbox has a numeric value.
>
> Now all I want to do is add them up when they get ticked, and the total
> value to appear in the text field, or subtract the value of the checkbox
> from the total if it is unchecked. I want this to happen automatically.
>
> Here is what I am trying, but as yet it is not working.
> function calculate(what) {
> for (var i=1,answer=0;i<9;i++)
> answer += what.elements['Checkbox' + i].value - 0;
> what.answer.value = answer;
> }
A checkbox has a value, and a 'checked' attribute of true or false;
they aren't related. So you're adding the values for *all* the boxes,
regardless of whether they're checked. Well, actually, one less than
all, since your loop starts at 1 and ends at 8 :-)
> <form ID="Form2">
> <INPUT type="checkbox" ID="Checkbox1" NAME="Checkbox1" VALUE="1"
> onchange="calculate(this.form)">
You might want to avoid all the looping, and use a global variable
for the value to pass to your display field; something like --
<script type="text/javascript">
var calculatedValue = 0;
function calculate(what) {
var change = 0;
change = ( what.checked )? (what.value - 0) : (0 - what.value);
calculatedValue = calculatedValue + change;
document.getElementById("Text13").value = calculatedValue;
}
</script>
Note the change in the onchange here:
<input onchange="calculate(this)">
HTH!
--
Hassan Schroeder ----------------------------- hassan at webtuitive.com
Webtuitive Design === (+1) 408-938-0567 === http://webtuitive.com
dream. code.
More information about the Javascript
mailing list