I’m making a simple client-side, self-grading quiz.
I ask 6 questions and I want to alert the user with their score (keeping things simple). If they leave an answer blank, an alert will appear.
I’m new to javascript and don’t really know how to check individual form elements to see if they’re empty. I’m also having problems with getting my code to run.
JS
EDIT
function grade() {
var score = 0;
var elt = document.quiz;
// Check to see if no questions were left unanswered.
if elt.question1.value.length == 0 || elt.question2.value.length == 0 ||
elt.question3.value.length == 0 || elt.question4.value.length == 0 ||
elt.question5.value.length == 0 || elt.question6.value.length == 0
{
alert ("Whoops, you're missing an answer!")
}
if (elt.question1[1].checked) {
score += 1;
}
if (elt.question2[0].checked) {
score += 1;
}
if (elt.question3[0].checked == false && elt.question3[1].checked &&
elt.question3[2].checked == false && elt.question3[3].checked == false) {
score += 1;
}
if (elt.question4[0].checked == false && elt.question4[1].checked == false &&
elt.question4[2].checked == false && elt.question4[3].checked) {
score += 1;
}
elt.question5 = elt.question5.toLowerCase()
if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
score += 1;
}
elt.question6 = elt.question6.toLowerCase()
if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
score += 1;
}
score = score / 6 * 100;
score = score.toFixed(2);
alert("You scored " + score + "%");
return false; // Return true if you want the form to submit on validation/grade
}
You have a some significant errors in your markup:
formelement around each question. These should all be in oneformelement. (Also, each question be in aOLto number the question in series.)label‘s, so they’re selecting other elements when you click them (try question 3, first checkbox).grade()function on the form’ssubmithandler, and it needs to beonsubmit="return grade()", withgrade()returningfalsewhen it doesn’t “pass” to prevent form submission*.* Note, I set the
grade()function to alwaysreturn falsein the example. You would need to add the logic for when it would allow the form to submit.As far as the Javascript…
You need the
eltvariable to be equal to yourdocument.quiz(note, I changed the mainformto have aname="quiz"in your markup). You can useindexOf()instead of a regex if you just want to have a simple check (regex could check forageas a word, though).If you just want to make sure a text input is not empty, you can use
el.value.length != 0orel.value != ''.Also, looking at your grading code, if you want only one to be selected, you could use a radio, unless you want the person taking the quiz to not know if one or more were valid answers. But radio’s only allow you to select a single value.
HTML
Javascript
http://jsfiddle.net/BeD3Z/10/