How to validate several mcq questions using JavaScript? - javascript

I really need an immediate with Javascript.
I created a multiple choice question quiz in xhtml and tried to validate using Javascript. The problem is I'm able to display an alert message if any questions are unanswered, but I want to list out the unanswered question numbers in the same alert message. Please see the codes below.
<script type="text/javascript">
<!--
function validateRadio(radio) {
var retval = false
for ( var i = 0; i < radio.length; i++ ) {
if ( radio[i].checked ) retval = true;
}
return retval;
}
// to make sure all questions are answered
function validateForm(theForm) // to make sure all questions are answered
{
var retval = true;
if ( !validateRadio(theForm.q1) ) retval = false;
if ( !validateRadio(theForm.q2) ) retval = false;
if ( !validateRadio(theForm.q3) ) retval = false;
if ( !retval ) alert("Answer all of the questions");
return retval;
}
// --></script>
<form name="quiz" action="result.php" method="post">
<p>1. Choose the correct set of solution(s) by solving <img src="images/image002.png" width="93" height="17" alt=""/> equation?<br/>
<input type="radio" name="q1" value="1"/>gh<br/>
<input type="radio" name="q1" value="2"/>hk<br/>
<input type="radio" name="q1" value="3"/>h<br/>
<input type="radio" name="q1" value="4"/>ncb</p>
<p>2. What is the value of <i>x</i> when 78x ?<br/>
<input type="radio" name="q2" value="1"/>90<br/>
<input type="radio" name="q2" value="2"/>656<br/>
<input type="radio" name="q2" value="3"/>2<br/>
<input type="radio" name="q2" value="4"/>5</p>
<p>3. What is the value of 5x ?<br/>
<input type="radio" name="q3" value="1"/>+3<br/>
<input type="radio" name="q3" value="2"/>+6<br/>
<input type="radio" name="q3" value="3"/>-3<br/>
<input type="radio" name="q3" value="4"/>-6</p>
<p><input type="submit" name="submit" value="Submit Now!" onclick="return validateForm(this.form)"/></p>

Do this:
function validateForm(theForm) // to make sure all questions are answered
{
var retval = true;
var unanswered = "";
if ( !validateRadio(theForm.q1) ){retval = false;unanswered += "Question1\n";}
if ( !validateRadio(theForm.q2) ){retval = false;unanswered += "Question2\n";}
if ( !validateRadio(theForm.q3) ){retval = false;unanswered += "Question3\n";}
if ( !retval ) alert("Answer all of the questions\nThe following were unanswered:\n" + unanswered);
return retval;
}

Related

change label text of all radio button in quiz as red and green

Below is the code of a sample radio button quiz where multiple radio buttons are provided. Correct answers and wrong answers are defined in the code. User may check any answer or keep all blank. If user checks any radio button and finally clicks "Grade Me" button, label text of radio button of any wrong answers checked by the user shall appear as red and at the same time correct answer of that particular question shall appear in green (This will help the user know which question he answered wrong and what is its correct answer). I have tried several steps and searched many forums and failed. I think it will be really simple.
Example:
var numQues = 3;
var numChoi = 3;
var answers = new Array(3);
answers[0] = "doesn't like";
answers[1] = "don't come";
answers[2] = "come";
var wrong = new Array(3);
wrong[0] = "don't like";
wrong[1] = "doesn't come";
wrong[2] = "comes";
var wrong1 = new Array(3);
wrong1[0] = "doesn't likes";
wrong1[1] = "doesn't comes";
wrong1[2] = "coming";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < numQues; i++) {
currElt = i * numChoi;
answered = false;
for (j = 0; j < numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
answered = true;
if (currSelection.value == answers[i]) {
score += 3;
break;
}
if (currSelection.value == wrong[i]) {
score -= 1;
break;
}
if (currSelection.value == wrong1[i]) {
score -= 1;
break;
}
}
}
}
var scoreper = Math.round(score * 100 / 9);
form.percentage.value = scoreper + "%";
form.mark.value = score;
}
<title>Quiz Questions And Answers</title>
<center>
<h1>Quiz Questions</h1>
</center>
<p>
<form name="quiz">
<p>
<b><br>1. He -------------------- it.<br></b>
<label><input type="radio" name="q1" value="don't like">don't like</label><br>
<label><input type="radio" name="q1" value="doesn't like">doesn't like</label><br>
<label><input type="radio" name="q1" value="doesn't likes">doesn't likes</label><br>
<p><b>
<hr>
<br>2. They -------------------- here very often.<br></b>
<label><input type="radio" name="q2" value="don't come">don't come</label><br>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label><br>
<p><b>
<hr>
<br>3. John and Mary -------------------- twice a week.<br></b>
<label><input type="radio" name="q3" value="come">come</label><br>
<label><input type="radio" name="q3" value="comes">comes</label><br>
<label><input type="radio" name="q3" value="coming">coming</label>
<br>
<p><b>
<hr>
<p><b>
<input type="button"value="Grade Me"onClick="getScore(this.form);">
<input type="reset" value="Clear"><p>
Number of score out of 15 = <input type= text size 15 name= "mark">
Score in percentage = <input type=text size=15 name="percentage"><br>
</form>
<p>
<form method="post" name="Form" onsubmit="" action="">
</form>
Here is a rewrite of your code.
I fixed the illegal HTML and used best practices with event listeners, querySelectors and CSS
Please study the code and see if you understand. I can add more comments if needed
var answers = ["doesn't like","don't come","come"];
var rads, quiz; // need to be set after load
window.addEventListener("load",function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click",function(e) { // on click of scoreme
var score = 0;
for (var i=0;i<rads.length;i++) { // loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1)-1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = rad.value==answers[idx];
if (correct) {
rad.closest("label").classList.toggle("correct");
if (checked) score +=3;
}
else if (checked) {
score--;
rad.closest("label").classList.toggle("error")
}
}
var scoreper = Math.round(score * 100 / rads.length);
document.querySelector("#percentage").innerHTML = scoreper + "%";
quiz.mark.value = score;
});
});
.correct {
color: green
}
.error {
color: red
}
<title>Quiz Questions And Answers</title>
<div class="header">
<h1>Quiz Questions</h1>
</div>
<form id="quiz">
<div class="questions">
<p>
<b>1. He -------------------- it.</b><br/>
<label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
<label><input type="radio" name="q1" value="doesn't like" />doesn't like</label><br/>
<label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
</p>
<hr>
<p><b>2. They -------------------- here very often.</b><br/>
<label><input type="radio" name="q2" value="don't come">don't come</label><br/>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
</p>
<hr>
<p><b>3. John and Mary -------------------- twice a week.</b><br/>
<label><input type="radio" name="q3" value="come">come</label><br/>
<label><input type="radio" name="q3" value="comes">comes</label><br/>
<label><input type="radio" name="q3" value="coming">coming</label><br/>
</p>
<hr>
<p>
<input type="button" value="Grade Me" id="scoreButton">
<input type="reset" value="Clear"><br/>
Number of score out of 15 = <input type="text" size="15" id="mark">
Score in percentage = <span id="percentage"></span>
<p>
</div>
</form>
In your getScore function, when you find out that a certain element has a correct answer selected (whichever var is the label - unless you are using a custom radio button which I would recommend since changing the background of the label element would simply highlight the words), you can give it a new class using JS.
currSelection.classList.add("correct");
or
currSelection.classList.add("incorrect");
Then in your CSS file you can have rules saying
.correct { background: green !important; }
.incorrect { background: red !important; }
WoW!....Close....Thanks for support. But still all the wrong answers are showing red color. This will let the user know which question he answered wrong. That part is Okay. But once the wrong answers are marked with red(I mean only the wrongly selected radio button choice texts and not the entire question and answer choices
the correct answer of that wrong attempt to be shown in green to enlighten the user. And the sad part is that I again failed with the CSS thing. I wanted to create a quiz in blog and added custom CSS with conditional tag in html of blogger post.....Not Working. However, I will add the modified code here so that you get a clear picture if I am doing rightly as you said.(How and where to add the CSS rules inside this code(if that is what you mean))
var answers = ["doesn't like", "don't come", "come"];
var rads, quiz; // need to be set after load
window.addEventListener("load", function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click", function(e) { // on submit
var score = 0;
var checked = quiz.querySelectorAll("input[type=radio]:checked"); // all checked radios
for (var i = 0; i < checked.length; i++) { // loop over all checked radios in the form
var idx = checked[i].name.substring(1) - 1; //remove the q from the name - JS arrays start at 0
var correct = checked[i].value == answers[idx];
checked[i].closest("p").classList.toggle("error", !correct)
checked[i].closest("p").classList.toggle("correct", correct)
score += correct ? 3 : -1; // this is called a ternary
}
var scoreper = Math.round(score * 100 / rads.length);
document.querySelector("#percentage").innerHTML = scoreper + "%";
quiz.mark.value = score;
});
});
<!DOCTYPE HTML>
<html>
<body>
<title>Quiz Questions And Answers</title>
<div class="header">
<h1>Quiz Questions</h1>
</div>
<form id="quiz">
<div class="questions">
<p>
<b>1. He -------------------- it.</b><br/>
<label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
<label><input type="radio" name="q1" value="doesn't https://stackoverflow.com/questions/53818896/change-label-text-of-all-radio-button-in-quiz-as-red-and-green/59801712#like" />doesn't like</label><br/>
<label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
</p>
<hr>
<p><b>2. They -------------------- here very often.</b><br/>
<label><input type="radio" name="q2" value="don't come">don't come</label><br/>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
</p>
<hr>
<p><b>3. John and Mary -------------------- twice a week.</b><br/>
<label><input type="radio" name="q3" value="come">come</label><br/>
<label><input type="radio" name="q3" value="comes">comes</label><br/>
<label><input type="radio" name="q3" value="coming">coming</label><br/>
</p>
<hr>
<p>
<input type="button" value="Grade Me" id="scoreButton">
<input type="reset" value="Clear"><br/> Number of score out of 15 = <input type="text" size="15" id="mark"> Score in percentage = <span id="percentage"></span>
<p>
</div>
</form>
</body>
</html>
You can try this:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var coffee = document.forms[0];
var txt = "";
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
document.getElementById("score"+i).style.color = "green";
document.getElementById("order").value = "You Clicked Option " + i;
}
} }
</script>
</head>
<body>
<div id="score1" style="font-size: 50px">1</div>
<div id="score2" style="font-size: 50px">2</div>
<div id="score3" style="font-size: 50px">3</div>
<div id="score4" style="font-size: 50px">4</div>
**<form action="/action_page.php">
<input type="text" id="order" size="50">
<br>
<input type="radio" name="coffee" value="1" onclick="myFunction()">Option 1<br>
<input type="radio" name="coffee" value="2" onclick="myFunction()">Option 2<br>
<input type="radio" name="coffee" value="3" onclick="myFunction()">Option 3<br>
<input type="radio" name="coffee" value="4" onclick="myFunction()">Option 4<br>
</form>**
</body>
</html>

Making javascript check what radio form has been selected

I am trying to make a dog race.
Basically what I want is to check what radio the user checked,
compare it to a random number between 1 - 5 and see if he won.
My question is... How do I compare them?
This is my code so far.
function chooser(){
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
document.getElementById("winner").innerHTML = rand;
if(pick == rand)
{document.getElementById("winner").innerHTML =("win!");}
else {
document.getElementById("winner").innerHTML =("loose");
}
}
HTML:
<form id="pick" action="rand">
<input type="radio" name="dog" id="dog1">Dog1<br>
<input type="radio" name="dog" id="dog2">Dog2<br>
<input type="radio" name="dog" id="dog3">Dog3<br>
<input type="radio" name="dog" id="dog4">Dog4<br>
<input type="radio" name="dog" id="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" value="Gamble" onclick="chooser();">
<br>
<p id="winner"> </p>
A jQuery and Native JavaScript Approach. Take your pick.
$("#submitjq").click(function() {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = $("input[type=radio][name='dog']:checked").val();
if(pick == rand)
{
$("#winner").html("jQuery: Won!");
}
else {
$("#winner").html("jQuery: Lost!");
}
});
document.getElementById('submitjs').onclick = function () {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = document.pick.dog.value;
console.log(pick);
if(pick == rand)
{
document.getElementById("winner").innerHTML = "JavaScript: Won!" ;
}
else {
document.getElementById("winner").innerHTML = "JavaScript: Lost!" ;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="pick" name="pick" action="rand">
<input type="radio" name="dog" value="dog1">Dog1<br>
<input type="radio" name="dog" value="dog2">Dog2<br>
<input type="radio" name="dog" value="dog3">Dog3<br>
<input type="radio" name="dog" value="dog4">Dog4<br>
<input type="radio" name="dog" value="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" id="submitjs" value="Gamble Native JavaScript" />
<input type="submit" id="submitjq" value="Gamble jQuery" />
<br>
<p id="winner"> </p>
You need to give each radio button a value, and then getElementsByName, iterating through to find the one that's checked. See similar thread...

Creating a multiple choice option in javascript

I have created an HTML multiple choice question. I am facing a problem how to validate it. Below is the HTML code:
<h1>JavaScript is ______ Language.</h1><br>
<form>
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button>Submit Answer</button>
When the user clicks the submit button, there should be an alert that will show a message based on what was selected.
If no option was selected, the alert box should say "please select choice answer".
If the "Scripting" option was selected, the alert box should say "Answer is correct !"
If an option different from "Scripting" is selected, the alert box should say "Answer is wrong".
I want to create this validation in JavaScript.
You have to use onclick attribute and more js
attach event hander to your button
get radio elements value
compare
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
Some changes
I made some changes to the code above to make it more 'abstract'
<h1>JavaScript is ______ Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer(d1.choice.value, 'Scripting')">Submit Answer</button>
<script>
var submitAnswer = function(valore, rightanswer) {
if (valore == rightanswer) {
alert("OK");
}
};
</script>
Another, more complex example
<div style="background-color:lightblue">
<h1>JavaScript is a <span id='a1'>______</span> Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Scripting', 'd1','a1')">
</form>
</div>
<div style="background-color:lightblue">
<h1>Python is a <span id='a2'>______</span> Language.</h1><br>
<form id="d2">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Wonderful"> Wonderful
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Wonderful', 'd2', 'a2')">
</form>
</div>
<script>
var validate = function(valore, rightanswer, form, span) {
var formname = document.getElementById(form)
var spanname = document.getElementById(span)
spanname.innerHTML = rightanswer;
if (valore == rightanswer) {
formname.innerHTML ="<div style='background-color:lightgreen'><h1>GREAT! YOU'RE RIGHT: The answer, in fact, was: " + rightanswer + "</h1></div>";
}
else {
formname.innerHTML ="<div style='background-color:pink'><h1>Sorry, you where wrong: The answer was: " + rightanswer + "</h1></div>";
}
};
</script>
Use the required keyword. This prompts the user to choose a value, when the submit button is pressed without choosing any option. And always prefer to use
<input type="submit" value="submit"> over <button>Submit Answer</button>
while handling forms. Use the onclick() event handler to call your Javascript code.
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting" required> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<input type="submit" value="submit" onclick="validate()">
</form>
And the javascript part is as follows.
<script type="text/javascript">
function validate() {
var a= document.getElementByName("choice");
for (var i = 0, i < a.length; i++) {
if (a[i].checked) {
if( a[i].value == "scripting" )
alert("your answer is correct");
else
alert("your answer is not correct");
break;
} } }
</script>
Here condition is showing in alert pop up box. but I want to show it in a html tag.
But after clicking submit button, innerHTML content showing a millisecond and then automatic remove the content. How selection will stay in innerHTML
document.getElementById("answer").innerHTML;
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
document.getElementById("answer").innerHTML = "please select choice answer";
} else if ( val == "Scripting" ) {
document.getElementById("answer").innerHTML = "Answer is correct !"
} else {
document.getElementById("answer").innerHTML = "Answer is wrong"
}
};
You can add a function and event onClick so that whenever someone clicks on option submit button will appear.

How to connect array elements with radio buttons

I'm trying to make a simple quiz with radio button options. The quiz has one button that should dynamically remove and add the next question, and set of radio buttons. The questions and options stored in separate arrays. I am stuck on trying to connect each option with a radio button. Any ideas how to go about with this?
P.S. Just started learning JS as you might tell from my code
<script type="text/javascript">
var questionsArray = new Array();
questionsArray[0] = "1. Who's the president of the US?";
questionsArray[1] = "2. What is the capital city of France?";
questionsArray[2] = "3. What is your favorite food?";
var choicesArray = new Array();
choicesArray[0] = ["Lebron James", "Barack Obama", "George Bush","George Clooney"];
choicesArray[1] = ["Nairobi","London","Paris","Sydney"];
choicesArray[2] = ["Pizza","Sushi","Pasta","Lobster"];
function createRadioElement(name){
var radioHTML = '<input type="radio" name="'+name+'"'+'/>';
var radioFragment = document.createElement("div");
radioFragment.innerHTML = radioHTML;
return radioFragment.firstChild;
}
var index = -1;
function questionSwapOnclick(){
while(index < questionsArray.length){
index++;
document.getElementById("question").innerHTML = questionsArray[index];
if(document.getElementById("question").innerHTML == "undefined"){
document.getElementById("question").innerHTML = "Finished the quiz!"
document.getElementById("choices").innerHTML = ""
}
var splitChoices = choicesArray[index].join("<br />");
document.getElementById("choices").innerHTML = splitChoices;
return true;
}
}
</script>
Why not keep the questions in the html?
JS Fiddle
<form id="questions">
<div class="question active">
<p>1. Who's the president of the US?</p>
<label>
<input type="radio" name="q1" value="1">Lebron James</label>
<label>
<input type="radio" name="q1" value="2">Barack Obama</label>
<label>
<input type="radio" name="q1" value="3">George Bush</label>
</div>
<div class="question" style="display: none;">
<p>2. What is the capital city of France?</p><label>
<input type="radio" name="q2" value="1">Nairobi</label>
<label>
<input type="radio" name="q2" value="2">London</label>
<label>
<input type="radio" name="q2" value="3">Paris</label>
</div>
<div class="question" style="display: none;">
<p>3. What is your favorite food?</p>
<input type="radio" name="q3" value="1">Pizza</label>
<label>
<input type="radio" name="q3" value="2">Sushi</label>
<label>
<input type="radio" name="q3" value="3">Pasta</label>
</div>
<hr> Next question ยป
// used jquery 1.11.0
$(function () {
var questions = $('#questions');
var next_btn = $('#next');
next_btn.on('click', function () {
var active_question = questions.find('.active');
if (active_question.find('input[type=radio]:checked').length) {
active_question.slideUp(500, function(){
active_question.removeClass('active');
});
if(active_question.next('.question').length){
active_question.next('.question').addClass('active').slideDown(500);
}
else {
alert('Thank you!');
alert(questions.serialize());
questions.hide();
}
}
else {
alert('Select answer!');
}
});
});

How to check if everything in the loop is true?

I have a simple multiple question form, each question has 4 answers and users must select 1 answer for each question.
So far I can check for an unanswered question and show an error message.
But now if all questions have been answered, I need the form to go to a results page (I assume window.location?)
How can I check if all questions have been answered?
$('.submit-button').click(function(event){
$('.validate-message').hide();
for (var i=1;i<6;i++) {
var input = $("input[name=q"+i+"]");
var inputChecked = $("input[name=q"+i+"]:checked");
if (!inputChecked.val()) { //if an answer is not selected for a question
$(input).parents('fieldset').append('<div class="validate-message" style="color:red;">Please choose an answer!</div>');
} else { // if an answer is selected for a question
}
}
return false;
});
Just use a boolean variable:
$('.submit-button').click(function(event){
var noErrors = true; // default to no errors
$('.validate-message').hide();
for (var i=1;i<6;i++) {
var input = $("input[name=q"+i+"]");
var inputChecked = $("input[name=q"+i+"]:checked");
if (!inputChecked.val()) { //if an answer is not selected for a question
noErrors = false; // an error was found, set noErrors to false
$(input).parents('fieldset').append('<div class="validate-message" style="color:red;">Please choose an answer!</div>');
} else { // if an answer is selected for a question
}
}
if(noErrors) // do stuff
return false;
});
Out of interest, here's a plain javascript solution.
Assuming HTML something like the following:
<form id="f0" onsubmit="return validateForm(this);">
<div>
<p>Question 1.<br>
A<input type="radio" value="A" name="q1"><br>
B<input type="radio" value="B" name="q1"><br>
C<input type="radio" value="C" name="q1"><br>
D<input type="radio" value="D" name="q1"><br>
</p>
<p>Question 2.<br>
A<input type="radio" value="A" name="q2"><br>
B<input type="radio" value="B" name="q2"><br>
C<input type="radio" value="C" name="q2"><br>
D<input type="radio" value="D" name="q2"><br>
</p>
<input type="reset" value="Clear answers">
<input type="submit" value="Submit answers">
</div>
</form>
A function to validate that each question has been answered is:
function validateForm(form) {
var control, controls = form.elements;
var visited = {};
var name, radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
name = control.name;
if (control.type == 'radio' && name && !visited.hasOwnProperty(name)) {
visited[name] = false;
radios = form[name];
for (j=0, jLen=radios.length; j<jLen; j++) {
visited[name] = visited[name] || radios[j].checked;
}
if (!visited[name]) {
// Question hasn't been answered, cancel submit and do whatever
alert('There are unanswered questions for ' + name);
return false;
}
}
// Validation for other controls
// ...
}
}

Categories

Resources