Javascript: adding up groups of text boxes

Associate
Joined
2 Aug 2005
Posts
680
I've written a little script to add up a group of 8 boxes, I just can't figure out how to make this work for a page of 7 groups of 8 boxes (hope that makes sense :) ). Here's the code so far:

Code:
function add() {

my = document.totals;

		var box1 = parseInt(my.g1a1.value,10);
		var box2 = parseInt(my.g1a2.value,10);
		var box3 = parseInt(my.g1a3.value,10);
		var box4 = parseInt(my.g1a4.value,10);
		var box5 = parseInt(my.g1a5.value,10);
		var box6 = parseInt(my.g1a6.value,10);
		var box7 = parseInt(my.g1a7.value,10);
		var box8 = parseInt(my.g1a8.value,10);
		
		gtotal = box1 + box2 + box3 + box4 + box5 + box6 + box7 + box8;
		
		if (isNaN(gtotal)) {
		my.total1.value = "Please distribute only numbers";
		
		} else if (gtotal < 10) {
		my.total1.value = "Add " + (10 - gtotal);
		
		} else if (gtotal > 10) {
		my.total1.value = "Subtract " + (gtotal - 10);
		
		} else {
		my.total1.value = gtotal;
		}

}
Here's the boxes html:

Code:
<li class="answer"><input type="text" name="g1a1" id="g1a1" value="0" onKeyUp="add()"></li>
			<li class="answer"><input type="text" name="g1a2" id="g1a2" value="0" onKeyUp="add()"></li>
			<li class="answer"><input type="text" name="g1a3" id="g1a3" value="0" onKeyUp="add()"></li>
			<li class="answer"><input type="text" name="g1a4" id="g1a4" value="0" onKeyUp="add()"></li>
			<li class="answer"><input type="text" name="g1a5" id="g1a5" value="0" onKeyUp="add()"></li>
			<li class="answer"><input type="text" name="g1a6" id="g1a6" value="0" onKeyUp="add()"></li>
			<li class="answer"><input type="text" name="g1a7" id="g1a7" value="0" onKeyUp="add()"></li>
			<li class="answer"><input type="text" name="g1a8" id="g1a8" value="0" onKeyUp="add()"></li>
			<li class="answer"><input type="text" name="total1" id="total1" value="0"></li>

Currently the Javascript adds up all the numbers from the boxes and puts the comment in the last box, but I have 6 other groups of these and the name structure for the next one is 'g2a1' and the total is called 'total2' and so on. I was thinking about adding a parameter to the add() function, any ideas?
 
Back
Top Bottom