Reputation: 61
I've gotten the code to work, however I wanted to know why it only works when there is more than one checkbox
named the same thing. I want each checkbox
to have it's own name but still add together. Any help would be appreciated. Here is my code:
function checkTotal() {
document.listForm.total.value = '';
var sum = 0;
for (i=0;i<document.listForm.choicea.length;i++) {
if (document.listForm.choicea[i].checked) {
sum = sum + parseInt(document.listForm.choicea[i].value);
}
if (document.listForm.choiceb[i].checked) {
sum = sum + parseInt(document.listForm.choiceb[i].value);
}
}
document.listForm.total.value = sum;
}
<form name="listForm">
<input type="checkbox" name="choicea" value="2" onchange="checkTotal()"/>2<br/>
<input type="checkbox" name="choicea" value="5" onchange="checkTotal()"/>5<br/>
<input type="checkbox" name="choiceb" value="10" onchange="checkTotal()"/>10<br/>
<input type="checkbox" name="choiceb" value="20" onchange="checkTotal()"/>20<br/>
Total: <input type="text" size="2" name="total" value="0"/>
</form>
Upvotes: 0
Views: 1046
Reputation: 11751
If there is only one checkbox with a name, then the JavaScript binding will not be an array, e.g. it will not be choicea[0]
it will just be choicea
.
You can give each item the same class name and use getElementsByClassName
(IE9 or above, IE8 and below will require a shim), which always returns an array of items (well, a HTMLCollection
actually).
Upvotes: 1
Reputation: 6359
You're using the "choicea"/"choiceb" as an array in each instance. If there is only one of each name, it won't be an array. Consider just using an jQuery and an input selector rather than using the old .form.control method, it'll probably be easier. Use $("myselector").each or similar. If not, you could consider GetElementsByTagName as an alternative.
Upvotes: 0