Learning JS, trying to get this little survey to work, but I get a "function not defined" error at HTML element onclick. Can't figure out why, it seems like the function is defined and I can't find any syntax errors. I also get an error saying that "soda is not defined," but it seems like that variable is defined as an object in the array.
<html>
<body>
<h3>What cats are in the room?</h3>
Sophie: <input type="checkbox" id="sophieCheck">
<br></br>
Soda: <input type="checkbox" id="sodaCheck">
<br></br>
Mr.: <input type="checkbox" id="mrCheck">
<br></br>
<button onclick="catsInTheRoom()">Try it</button>
<br></br>
<p id="cats"></p>
<script>
function catsInTheRoom() {
var myCats = [ soda, mr, sophie ];
if (getElementById("sodaCheck").checked) {
myCats[0] = 1;
} else {
myCats[0] = 0;
}
if (getElementById("sophieCheck").checked) {
myCats[2] = 10;
} else {
myCats[2] = 0;
}
if (getElementById("mrCheck").checked) {
myCats[1] = 20;
} else {
myCats[1] = 0;
}
getElementById("cats").innerHTML = myCats[0] + myCats[1] + myCats[2];
}
</script>
</body>
</html>
I created the array so I can use the numerical values for a switch statement to produce different text based on which checkboxes are checked.
This simpler version worked:
Sophie: <input type="checkbox" id="sohpieCheck">
<br></br>
Soda: <input type="checkbox" id="sodaCheck">
<br></br>
Mr.: <input type="checkbox" id="mrCheck">
<br></br>
<button onclick="myFunction()">Try it</button>
<p id="cats"></p>
<script>
function myFunction() {
var soda = document.getElementById("sodaCheck").checked;
if (soda) {
catBehavior = "Cats are being rascals.";
} else {
catBehavior = "Cats are behaving nicely.";
}
document.getElementById("cats").innerHTML = catBehavior;
}
</script>
Why does the second example work, but not the first one?