I am having some trouble getting my form to work on a web page. I have several text boxes and want to calculate how many are checked. However, I am getting an error message in the console that says it can't read the property 'checked' of null. When I ask it to read the property 'checked' of the element "top1" (by changing "top" + i to "top1"), it works. Any ideas?
Furthermore, the total is added to and reported during every iteration of my 'for' loop, but when it is outside the loop, nothing is printed in the console. I have a hunch it has to do with the error described above.
Any help would be greatly appreciated! Thanks!
A sample of my HTML code:
Which toppings would you like? <br>
<input type="checkbox" id="top0" value="pepperoni"> pepperoni <br>
<input type="checkbox" id="top1" value="ham"> ham <br>
<input type="checkbox" id="top2" value="meatballs"> meatballs <br>
<input type="checkbox" id="top3" value="chicken"> chicken <br>
<br>
<br>
<input type="button" id="calculate" onclick="calc()" value="Calculate"><br>
</form>
Here is my javaScript code:
function calc() {
var total = 0;
var topping;
for (i = 0; i <= 3; i++) {
topping = document.getElementById("top" + i);
if (topping.checked == true) {
total++;
}
console.log(total);
}
}
Aucun commentaire:
Enregistrer un commentaire