View Full Version : adding and subtracting checkboxes

07-02-2003, 02:38 AM

I have a set of checkboxes and I want the script to add the values when checked but subtract when unchecked.

I can do the check part but have no idea how to deduct from the total when someone unchecks the box(es).

<script type="text/javascript">
function test(val){
var all = 0;

el = document.form1.total;
all += parseInt(el.value) + parseInt(val);

document.form1.total.value = all;




<form name="form1">
$1 <input type="checkbox" name="check1" value="1" onClick="test(1)"> <BR>
$2 <input type="checkbox" name="check2" value="2" onClick="test(2)"> <BR>
$3 <input type="checkbox" name="check3" value="3" onClick="test(3)"> <BR>
<input type="text" name="total" value="0">



07-02-2003, 03:02 AM
<script type="text/javascript">

function sum(oCheckbox) {
var fieldnames = ['check1' , 'check2' , 'check3']; //fields to sum, in array
var field, total = 0, oForm = oCheckbox.form; //initialize total, get form object
for (var i=0; i<fieldnames.length; ++i) { //loop
field = oForm.elements[fieldnames[i]]; //get element
if (field.checked) //checked?
total += parseInt(field.value); //add it
oForm.elements.total.value = '$' + total; //output

<form name="form1">
$1 <input type="checkbox" name="check1" value="1" onclick="sum(this)"><BR>
$2 <input type="checkbox" name="check2" value="2" onclick="sum(this)"><BR>
$3 <input type="checkbox" name="check3" value="3" onclick="sum(this)">
<input type="text" name="total" value="$0">