Very nice, Trinithis. You inspired me to go ahead and add the events onload:
Code:
<script type="text/javascript">
function calc(start, end, totalIndex) {
for(var i=start, sum = 0; i<=end; i++) {
sum += parseInt(document.forms.form1.elements['A'+i].options[document.forms.form1.elements['A'+i].selectedIndex].text);
}
document.forms.form1.elements['total'+totalIndex].value = sum;
}
onload=function(){
var group=[]; group[0]=[];
for (var i = 0, g=0, els = document.forms.form1.elements; i < els.length; i++)
if(els[i].tagName.toLowerCase()=='select')
group[g][group[g].length]=els[i];
else
group[g=group.length]=[];
for (var i = 0, s=1, e=0; i < group.length; i++){
e=e+group[i].length;
for (var j = 0; j < group[i].length; j++)
group[i][j].onfocus=group[i][j].onchange=new Function('calc('+s+','+e+','+[i+1]+')');
s=s+group[i].length;
}
}
</script>
This works out well with the example markup minus the events, example group:
HTML Code:
<form name="form1" action="cgi-bin/news/maika-register2.pl" method=POST>
<div align="center"><center><b><u>NEW CLIENT REGISTRATION FORM</u></b><br>Please complete the form below.<br>
</center></div><div align="center"><center>
<table border="0" width="600" cellspacing="1" cellpadding="0" height="712" >
<tr>
<td width="600" colspan="2" height="21">Response Questions:</td>
</tr>
<tr>
<td width="50" height="21" align="right"><select NAME="A1" id="A1">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select></td>
<td width="550" height="21" align="left"><p align="left">1 - Alcohol</td>
</tr>
<tr>
<td width="50" height="21" align="right"><select NAME="A2" id="A2">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select></td>
<td width="550" height="21"><p align="left">2 - Artificial sweeteners</td>
</tr>
<tr>
<td width="50" height="21" align="right"><select NAME="A3" id="A3">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select></td> . . .
. . . th="50" height="21" align="right"><select NAME="A19" id="A19">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select></td>
<td width="550" height="21"><p align="left">19 - Water, well</td>
</tr>
<tr>
<td width="50" height="21" align="right"><select NAME="A20" id="A20">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select></td>
<td width="550" height="21"><p align="left">20 - Diet often for weight control<br></td>
</tr>
<tr>
<td width="50" height="21" align="right"><input readonly type="text" type="text" NAME="total1" size="3">
</td>
<td width="550" height="21"><p align="left">Sum: This number is the sum of selection 1-20 and will be written to the database in field named "Total1"<br></td>
</tr>
Bookmarks