How to check if everything in the loop is true? - javascript

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
// ...
}
}

Related

form JavaScript function checkAnswer not loading pages

I have a form that I've been working on for a school project and I can't figure out what's wrong with the JavaScript checkAnswer function. The form and all the buttons work, but when I hit the submit button, all that loads is a blank page. I have tried researching forms but I can't figure out where my code is wrong. Why won't it check anything?
Here is the form from my index.html file:
<script src="CheckForm.js"></script>
<form method="post" action="return checkAnswer(this, '1', 'Correct.html',
'Incorrect.html');" name="quizForm" id="quizForm">
<input type="radio" name="choice" value="1"/>
<script>getMusician(answer1);</script><br/>
<input type="radio" name="choice" value="2"/>
<script>getMusician(answer2);</script><br/>
<input type="radio" name="choice" value="3"/>
<script>getMusician(answer3);</script><br/>
<input type="radio" name="choice" value="4"/>
<script>getMusician(answer4);</script><br/>
<input type="submit" value="Submit"/>
</form>
This is the code from my CheckForm.js file:
function checkAnswer(quizForm, Answer, CorrectPage, IncorrectPage)
{
var i = 0;
var j = null;
for(;i<quizForm.elements.length();i++)
{
if(quizForm.elements[i].value.checked)
j = quizForm.elements[i].value;
}
if(j === null)
{
windows.alert("Please make a selection.");
return false;
}
if(j == Answer)
{
document.location.href = CorrectPage;
}
else
{
document.location.href = IncorrectPage;
}
return false;
}
You shouldn't need a form for this. It looks like you are creating a static site so I would remove the form and the rest you are pretty close with. Here is a working example for you.
Also it looks like you are creating some sort of quiz site. Be aware users can use the developer console to see the correct answer (the first input to checkAnswer() method)- I thought it would be worth mentioning that.
function checkAnswer(answer, correctPage, incorrectPage) {
var i = 0;
var j = null;
var inputs = document.getElementsByClassName('musician');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
j = inputs[i].value;
}
if (j == null) {
alert("Please make a selection.");
return false;
}
if (j == answer) {
console.log('CORRECT!')
document.location.href = CorrectPage;
} else {
console.log('incorrect :(')
document.location.href = IncorrectPage;
}
}
<div id="inputContainer">
<input type="radio" name="choice" class="musician" value="1" />musician 1
<br/>
<input type="radio" name="choice" class="musician" value="2" />musician 2
<br/>
<input type="radio" name="choice" class="musician" value="3" />musician 3
<br/>
<input type="radio" name="choice" class="musician" value="4">musician 4
<br/>
</div>
<input type="button" onclick="checkAnswer('1', 'Correct.html',
'Incorrect.html')" value="Submit" />

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.

Checking if all my Radio Buttons are filled

I need to figure out how to check that my radio buttons are all filled. This is what I have but it only checks one button
var btns = form.choice_1;
for (var i=0; el=btns[i]; i++) {
if (el.checked) return true;
}
alert('Please select a radio button');
return false;
This is the form that I am taking input from.
<form onsubmit="return checkRadios(this);" name = "form" action = "like.php" method ="post" >
<h1> Questions </h1>
<p> Question 1 </p>
<input type="radio" name="choice_1" value="1">Like <input type="radio" name="choice_1" value="2" > Dislike
<p> Question 2 </p>
<input type="radio" name="choice_2" value="1">Like <input type="radio" name="choice_2" value="2" > Dislike
<p> Question 3 </p>
<input type="radio" name="choice_3" value="1">Like <input type="radio" name="choice_3" value="2" > Dislike
<p> Question 4 </p>
<input type="radio" name="choice_4" value="1">Like <input type="radio" name="choice_4" value="2" > Dislike
<br> <br>
<input type="submit" value="Submit">
Any help is appreciated.
Try this:
var checkRadios = function () {
var btns = form.querySelectorAll('input[name^=choice_][type="radio"]');
for (var i = 0; i < btns.length; i = i + 2) {
var check = true;
if (!btns[i].checked && !btns[i + 1].checked) check = false;
}
if (!check) alert('Please select a radio button');
return check;
}
var form = document.querySelector('form[name="form"]');
form.onsubmit = checkRadios;
Fiddle
You should use jQuery for this. It makes it much easier.
You would do it like this:
var e = ('#[[[[id of your radio]]]]');
if($e.is(':checked'){
//do what you need to
};
Try this. You will need jQuery.
checkRadios = function() {
if $("input:radio :checked").length == 0 {
alert('Please select a radio button');
return false;
}
}

How to validate several mcq questions using 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;
}

Adding form verification in this case

I've got 3 groups of radio buttons and 1 set of check boxes.
How do i check if a radio button is selected in each group of radio buttons and at least one check box is selected? And if not, maybe pop an alert window.
So thats : one radio button needs to be selected from all three groups and one check box (all four are mandatory). I've had no luck with this. Thanks
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
{
str += elem[i].value+"<br>";
}
}
document.getElementById('lblValues').innerHTML = str;
document.frmMain.reset();
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
Set 1
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<br>
Set 2
<INPUT TYPE="radio" NAME="r2" value="r2a">
<INPUT TYPE="radio" NAME="r2" value="r2b">
<INPUT TYPE="radio" NAME="r2" value="r2c">
<br>
Set 3
<INPUT TYPE="radio" NAME="r3" value="r3a">
<INPUT TYPE="radio" NAME="r3" value="r3b">
<INPUT TYPE="radio" NAME="r3" value="r3c">
<br>
Check 1
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Here's a modified version of your function:
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
var groups = { 'r1': 0, 'r2': 0, 'r3':0, 'c1': 0 };
for (var i = 0; i < elem.length; i++){
if (elem[i].checked) {
var n = elem[i].name;
groups[n] += 1
str += elem[i].value + "<br>";
}
}
document.getElementById('lblValues').innerHTML = groups['r1'] + "/" +
groups['r2'] + "/" + groups['r3'] + "/" + groups['c1'];
document.frmMain.reset();
}
In this function we count how many elements are checked (obviously one for radio button in the same group but you understand the principle and this is flexible) and groups[XXX] is the count (with XXX being the group name).
You can adjust to your needs and add the alert as requested.
You can do this in javascript by writing a lot of code or I strongly recommend using jquery validation plugin. Look at this example: http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html
You can do something like:
<input type="radio" validate="required:true" name="family" value="s" id="family_single" class="error">
Which will require at least one option being selected.
Also, its best to have inline feedback when something is not valid. Having alerts can be really annoying.
var radioCount = 0;
var checkBoxCount = 0;
var currentElement;
for (var i = 0; i < elem.length; ++i) {
currentElement = elem[i];
if (!currentElement.checked)
continue;
if (currentElement.type == "checkbox")
++checkBoxCount;
else if (currentElement.type == "radio")
++radioCount;
}
if (radioCount < 3)
//fail
if (checkBoxCount < 1)
//fail

Categories

Resources