I’m building a little js quiz game. With the code below, the user selects an answer and then has to click the answer button to submit, which checks whether the answer was correct. In other words, there’s two steps. First, select. Second, submit. I wanted to know if there’s a way to eliminate the second step, so that the event’s fired on selection.
Here’s a fiddle if necessary.
http://jsfiddle.net/mjmitche/D5H9z/
I guess I don’t know how to make a general event for all the select boxes that initiates the check, but then, at the same time, is able to inspect the selection to see if it’s correct, if that makes any sense.
Note, the game is eventually going to be using something like Underscore templates to insert questions and answer choices into the fields, so if that influences how you’d set things up, please take it into consideration.
Thank you in advance
html
<fieldset id="question1">
<legend>What is the answer to this question?</legend>
<label><input type="radio" name="q1" value="right"> Right answer</label>
<label><input type="radio" name="q1" value="wrong"> Wrong answer</label>
<ul>
</fieldset>
<input type="button" id="answer">
js
document.getElementById("answer").onclick = validate;
function validate() {
var radios;
var i;
var right;
radios = document.getElementById("question1").getElementsByTagName("input");
right = false;
for(i = 0; i < radios.length; i++) {
if(radios[i].value == "right" && radios[i].checked == true) {
right = true;
}
}
if(right) {
alert("You answered correctly");
} else {
alert("Wrong answer");
}
}
Update, the final version of the game will be using Backbone, which supports events like this
events:{ 'click #sayhello': 'validate'
},
The first two answers to this question proposed an ‘inline’ solution, but I was hoping for something that would fit in with backbone’s event handling. What would I replace #sayhello with in order to trigger the validate function in this code.
Apply an
onclickhandler to each radio button:fiddle here