Reputation: 7532
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;
});
Upvotes: 1
Views: 539
Reputation: 147363
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
// ...
}
}
Upvotes: 0
Reputation: 78630
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;
});
Upvotes: 1