Reputation: 11
I'm learning javascript, and for a class assignment I'm working on a simple quiz. Found here: http://redwood.colorado.edu/scho5922/dm2/projects/project1.html
My problem is that I can't get the radio buttons to validate correctly. This prevents the quiz score from being calculated. When you click enter it cycles through the questions, but choosing the correct answer doesn't increase the score. I've tested this by adding both an alert after the if statement and a button that displays the 'score' variable. There is no alert with the correct answer and the score button (not on current version) displays a score of 0.
JavaScript
<script>
var beers =[
["New World Porter", "Avery"],
["Ellie's Brown Ale","Avery"] ,
["Out of Bounds Stout","Avery"] ,
["Hazed & Infused Dry Hopped Ale", "Boulder Beer"],
["Sweaty Betty Blonde Ale", "Boulder Beer"],
["Mojo IPA", "Boulder Beer"],
["Mama's Little Yellow Pils", "Oskar Blues"],
["Dale's Pale Ale", "Oskar Blues"],
["G'Knight Imperial Red Ale","Oskar Blues"],
["Old Chub Scotch Ale","Oskar Blues"]
] ;
var score = 0;
var questionNum = 0;
var turns = 0;
function enterF (beer){
questionNum++;
turns++;
var question = "What brewery makes ";
document.getElementById("header").innerHTML= question + beers[questionNum][0];
var answer = document.getElementsByName("beerbut").value.checked;
if(answers[i].checked == beers[questionNum-1][1]){
score++;
alert(score);
}
}
</script>
HTML
<body onload="popup()">
<h1 id="header">What brewery makes New World Porter</h1>
<div class="buttons">
<form>
<label for="_avery"> Avery</label>
<input type="radio" name="beerbut" id="_avery" value="Avery">
<br><br>
<label for="_bb"> Boulder Beer</label>
<input type="radio" name="beerbut" id="_bb" value="Boulder Beer">
<br><br>
<label for="_oskar"> Oskar Blues</label>
<input type="radio" name="beerbut" id="_oskar" value="Oskar Blues">
<br><br>
<label for="lefthand"> Left Hand </label>
<input type="radio" name="beerbut" id="_lefthand" value="Left Hand">
<br><br>
<input type="button" name="enter" id="enterbut" value="enter" onClick="enterF()">
</form>
</div>
</body>
</html>
Upvotes: 0
Views: 3271
Reputation: 126
You're trying to get a value from multiple elements at the same time. That's not how you do it.
Change this in the javascript
var answer = document.getElementsByName("beerbut").value.checked;
For something like this
var elements = document.getElementsByName("beerbut");
for(i = 0; i < elements.length; i++){
if(elements[i].checked){
alert(elements[i].value);
}
}
Upvotes: 1