...

View Full Version : adding and subtracting checkboxes



autumnnn
07-02-2003, 02:38 AM
hi,

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).

<HTML>
<HEAD>
<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;

}

</script>


</HEAD>
<BODY>

<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>
<BR><BR>
<input type="text" name="total" value="0">





</form>


</BODY>
</HTML>

cheesebagpipe
07-02-2003, 03:02 AM
<html>
<head>
<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
}

</script>
</head>
<body>
<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)">
<BR><BR>
<input type="text" name="total" value="$0">
</form>
</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum