The following routine adds a number to the total each time the checkbox with an assigned number is checked. This works perfectly (Example 1). But when I try to assign a variable that was calculated previously (Example 2), it returns a NaN in the Total, Can someone help me fix this? Thanks.
Example 1. This works
Example 2. This returns a NaN in the Total field
Example 1. This works
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>
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="text" name="Item1cost" value="2" >2
<input type="checkbox" name="choice" value="Item1cost" onchange="checkTotal()"/><br>
<input type="text" name="Item2cost" value="5" >5
<input type="checkbox" name="choice" value="Item2cost " onchange="checkTotal()"/><br>
<input type="text" name="Item3cost " value="5" >5
<input type="checkbox" name="choice" value="Item3cost" onchange ="checkTotal()"/> <br>
<input type="test" name="Item4cost" value="20">20
<input type="checkbox" name="choice" value="Item4cost" onchange="checkTotal()"/> <br>
Total: <input type="text" size="4" name="total" value="0"/>
</form>
Comment