JavaScript Check Box Adding/Subtracting Snipit

30 November -0001

This function adds the values of checkboxes, as the boxes are checked thier value is dynamically updated, as the boxes are unchecked the value gets subtracted. Useful for maintaining accurate totals. Although there are many different ways to accomplish this 'running tally' I've provided two simple methods below. The first is more succinct, but the second may meet your needs better depending on requirements.

Demo:

2
5
10
20
Total:

Code:

<script type="text/javascript">
	function checkTotal() {
		document.listForm.total.value = '';
		var sum = 0;
		for (i=0;i<document.listForm.choice.length;i++) {
		  if (document.listForm.choice[i].checked) {
		  	sum = sum + parseInt(document.listForm.choice[i].value);
		  }
		}
		document.listForm.total.value = sum;
	}
</script>

<form name="listForm">
<input type="checkbox" name="choice" value="2" onchange="checkTotal()"/>2<br/>
<input type="checkbox" name="choice" value="5" onchange="checkTotal()"/>5<br/>
<input type="checkbox" name="choice" value="10" onchange="checkTotal()"/>10<br/>
<input type="checkbox" name="choice" value="20" onchange="checkTotal()"/>20<br/>
Total: <input type="text" size="2" name="total" value="0"/>
</form>


Demo:

List 1 (10)
List 2 (15)
Total Number:


Code:
<script type="text/javascript">
total = 0;
List1 = 1;
List2 = 1;

function addUp(num, x)
	 {	
	 	if (x == "List1" && List1 == 1) {
			temp = document.theForm.ttl.value;
		 	tempo = parseInt(temp);
		 	numo = parseInt(num);
			nwTemp = tempo + numo;
		 	document.theForm.ttl.value = nwTemp;
			List1 = 0;
			return List1;
		}
		if (x == "List1" && List1 == 0) {
			temp = document.theForm.ttl.value;
		 	tempo = parseInt(temp);
		 	numo = parseInt(num);
			nwTemp = tempo - numo;
		 	document.theForm.ttl.value = nwTemp;
			List1 = 1;
		}
		if (x == "List2" && List2 == 1) {
			temp = document.theForm.ttl.value;
		 	tempo = parseInt(temp);
		 	numo = parseInt(num);
			nwTemp = tempo + numo;
		 	document.theForm.ttl.value = nwTemp;
			List2 = 0;
			return List2;
		}
		if (x == "List2" && List2 == 0) {
			temp = document.theForm.ttl.value;
		 	tempo = parseInt(temp);
		 	numo = parseInt(num);
			nwTemp = tempo - numo;
		 	document.theForm.ttl.value = nwTemp;
			List2 = 1;
		}
		
	}
</script>

<form name="theForm">

<input type="checkbox" onclick="addUp(10, 'List1')">List 1 (10)<br/>
<input type="checkbox" onClick="addUp(15, 'List2')">List 2 (15)<br/>
Total Number:<input type="text" name="ttl" value=0>
</form>