I seem to be having some trouble validating a 4 question multiple choice quiz in JavaScript. Right now if none of the answers are selected the alert pops up, but if even only one answer is selected the alert doesn't pop. I'm running my function as an onclick for a submit button. I'm fairly new to JavaScript and JQuery but have other programming experience, so The problem is probably something simple but I cant see it.
The function is:
function quiz1(){
if (!$("input[#name=q1]:checked").val() ||
!$("input[#name=q2]:checked").val() ||
!$("input[#name=q3]:checked").val() ||
!$("input[#name=q4]:checked").val() ||
!$("input[#name=q5]:checked").val()
) {
alert("You're not done yet!");
}
}
The html is:
<p class="question">1. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>
</ul>
<p class="question">2. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">Answer 1</label><br/>
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">Answer 2</label><br/>
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">Answer 3</label><br/>
<input type="radio" name="q2" value="d" id="q2d"><label for="q2d">Answer 4</label><br/>
</ul>
<p class="question">3. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q3" value="a" id="q3a"><label for="q3a">Answer 1</label><br/>
<input type="radio" name="q3" value="b" id="q3b"><label for="q3b">Answer 2</label><br/>
<input type="radio" name="q3" value="c" id="q3c"><label for="q3c">Answer 3</label><br/>
<input type="radio" name="q3" value="d" id="q3d"><label for="q3d">Answer 4</label><br/>
</ul>
<p class="question">4. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q4" value="a" id="q4a"><label for="q4a">Answer 1</label><br/>
<input type="radio" name="q4" value="b" id="q4b"><label for="q4b">Answer 2</label><br/>
<input type="radio" name="q4" value="c" id="q4c"><label for="q4c">Answer 3</label><br/>
<input type="radio" name="q4" value="d" id="q4d"><label for="q4d">Answer 4</label><br/>
</ul>
<div class="submit">
<input type="submit" onclick="quiz1()" value="Check Answers">
</div>
You have some syntax errors in there.
before:
function quiz1(){
if (!$("input[#name=q1]:checked").val() ||
!$("input[#name=q2]:checked").val() ||
!$("input[#name=q3]:checked").val() ||
!$("input[#name=q4]:checked").val() ||
!$("input[#name=q5]:checked").val()
) {
alert("You're not done yet!");
}
}
After:
function quiz1(){
if (!$("input[name='q1']:checked").val() ||
!$("input[name='q2']:checked").val() ||
!$("input[name='q3']:checked").val() ||
!$("input[name='q4']:checked").val()
) {
alert("You're not done yet!");
}
}
so with jquery when you want to reference a name you have to type it just like the name attribute in the html that is true with any attribute selector E.G.(data='', ng-someting=''...) and also you had one to many inputs in there XD
here is a jsfiddle
Related
I am working on a project where I have created a form in react.js with radio buttons but handleChange event is not firing the correct value of selected radio button. When I select male the formData object still has an empty value of gender, when I select it again the value of gender in formData gets updated to 0 which is equal to female. Please help me know what is the problem with my code.
import React from "react"
function Questions(props) {
const [formData, setFormData] = React.useState({
age: "",
gender: "",
polyuria: "",
polydipsia: "",
weight_loss: "",
weakness: "",
polyphagia: "",
genital_thrush: "",
visual_blurring: "",
itching: "",
irritability: "",
delayed_healing: "",
partial_paresis: "",
muscle_stiffness: "",
alopecia: "",
obesity: ""
})
function handleChange(event) {
const name = event.target.name
const value = event.target.value
setFormData(prevFormData => ({
...prevFormData,
[name]: value
}))
console.log(formData)
}
return (
<div>
<h1>Here will be Questions</h1>
<div className="form">
<p id="age" name="age">How old are you?</p>
<input type="number" min="1.20" max="5" htmlFor="age" value={formData.age} name="age"
onChange={handleChange}/>
<p id="gender">What is your gender?</p>
<input type="radio" id="male" name="gender" value="1" htmlFor="gender"
onChange={handleChange} checked={formData.gender === "1"}/>Male
<input type="radio" id="female" name="gender" value="0" htmlFor="gender"
onChange={handleChange} checked={formData.gender === "0"}/>Female
<p>Do you suffer from Polyuria?</p>
<p>If you are unfamiliar, read about Polyuria here</p>
<label><input type="radio" id="yes" name="polyuria" value="1" onChange={handleChange} checked={formData.polyuria === "1"}/>Yes</label>
<label><input type="radio" id="no" name="polyuria" value="0" onChange={handleChange} checked={formData.polyuria === "0"}/>No</label>
<p>Do you suffer from Polydipsia?</p>
<p>If you are unfamiliar, read about Polydipsia here</p>
<label><input type="radio" id="yes" name="polydipsia" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="polydipsia" value="0" onChange={handleChange}/>No</label>
<p>Have you noticed sudden weight loss in yourself?</p>
<label><input type="radio" id="yes" name="weight_loss" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="weight_loss" value="0" onChange={handleChange}/>No</label>
<p>Do you feel more weakness than usual throughout the day?</p>
<label><input type="radio" id="yes" name="weakness" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="weakness" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from Polyphagia?</p>
<label><input type="radio" id="yes" name="polyphagia" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="polyphagia" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from Genital Thrush?</p>
<label><input type="radio" id="yes" name="genital_thrush" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="genital_thrush" value="0" onChange={handleChange}/>No</label>
<p>Have you noticed your vision blurring?</p>
<label><input type="radio" id="yes" name="visual_blurring" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="visual_blurring" value="0" onChange={handleChange}/>No</label>
<p>Do you duffer from unusual itching on your body?</p>
<label><input type="radio" id="yes" name="itching" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="itching" value="0" onChange={handleChange}/>No</label>
<p>Do you experience unusual irritability/ mood swings?</p>
<label><input type="radio" id="yes" name="irritability" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="irritability" value="0" onChange={handleChange}/>No</label>
<p>Have you noticed delayed healing of wounds/ scars?</p>
<label><input type="radio" id="yes" name="delayed_healing" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="delayed_healing" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from Partial paresis?</p>
<label><input type="radio" id="yes" name="partial_paresis" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="partial_paresis" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from muscle stiffness?</p>
<label><input type="radio" id="yes" name="muscle_stiffness" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="muscle_stiffness" value="0" onChange={handleChange}/>No</label>
<p>Do you suffer from Alopecia?</p>
<label><input type="radio" id="yes" name="alopecia" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="alopecia" value="0" onChange={handleChange}/>No</label>
<p>Are you obese?</p>
<label><input type="radio" id="yes" name="obesity" value="1" onChange={handleChange}/>Yes</label>
<label><input type="radio" id="no" name="obesity" value="0" onChange={handleChange}/>No</label>
<button>Predict</button>
</div>
<button onClick={props.toggleBack}>Back</button>
</div>
)
}
export default Questions
change your handle function to this
function handleChange(event) {
const name = event.target.name
const value = event.target.value
const updatedData = {...formData,[name]:value}
setFormData(updatedData)
console.log(formData)
}
currently your state update and render is not aligned.
The code has 3 form groups used for Y/N questions with html radio buttons.
<div class="form-group">
<p>Q1</p>
<input type="radio" name="q1" value="y">Yes
<input type="radio" name="q1" value="n">No
</div>
<div class="form-group">
<p>Q2</p>
<input type="radio" name="q2" value="y">Yes
<input type="radio" name="q2" value="n">No
</div>
<div class="form-group">
<p>Q3</p>
<input type="radio" name="q3" value="y">Yes
<input type="radio" name="q3" value="n">No
</div>
// Jquery code:
<script>
var x = 0;
$('input[name="q1"]').change(function() {
if ($(this).val() == 'y') {
var x = 1;
}
});
if(x==1){
alert('res');
}
</script>
If possible, please ignore my var setting try and share the answer on how to execute the same result if any radio button with value="y" is checked.
This part of your code doesn't work because at the page load (doc ready) your x is 0. var x = 0
if(x==1){
alert('res');
}
Here is the example on how to run console.log if 'yes' is checked on every radio
$('input[type="radio"]').change(function() {
if ($(this).val() == 'y') {
console.log('yes');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<p>Q1</p>
<input type="radio" name="q1" value="y">Yes
<input type="radio" name="q1" value="n">No
</div>
<div class="form-group">
<p>Q1</p>
<input type="radio" name="q2" value="y">Yes
<input type="radio" name="q2" value="n">No
</div>
<div class="form-group">
<p>Q1</p>
<input type="radio" name="q3" value="y">Yes
<input type="radio" name="q3" value="n">No
</div>
$('input[type="radio"]').click(function() {
if ($(this).val() == 'y') {
console.log('yes');
}
});
$ ('input [type='radio']') select all the input radio and onClick if the value of the input equal 'y' then it is the right answer
this seems super simple to me, but I just can't figure it out today.
I've developed a basic quiz, and want to add the answers of the quiz together to create a "score". Based on the score I'll return different results on the confirmation page.
Here's a basic example of the form:
<form id="quiz" method="post" name="quiz" action="url">
<label for="field1">Question 1</label>
<label><input name="question1" value="1" type="radio">Answer 1</label>
<label><input name="question1" value="4" type="radio">Answer 2</label>
<label><input name="question1" value="9" type="radio">Answer 3</label>
<label for="field2">Question 2</label>
<label><input name="question2" value="1" type="radio">Answer 1</label>
<label><input name="question2" value="4" type="radio">Answer 2</label>
<label><input name="question2" value="9" type="radio">Answer 3</label>
<label for="field3">Question 3</label>
<label><input name="question3" value="1" type="radio">Answer 1</label>
<label><input name="question3" value="4" type="radio">Answer 2</label>
<label><input name="question3" value="9" type="radio">Answer 3</label>
<input value="See your Results" type="submit">
</form>
I tried building out some javascript to add these values together, but it wasn't even beginning to work - here's my attempt in case you're curious:
function generateScore(){
var maturityScore = document.forms[0].question1.value + document.forms[0].question2.value + document.forms[0].question1.value;
document.forms[0].maturityLevel.value = maturityScore;
}
document.forms[0].addEventListener('submit') = generateScore
Can anyone point me in the right direction? Happy to use javascript or jquery to do this. Note that I can't edit the form html - it's being generated by the MAP I'm using (and is way ugly - the version I posted above is simplified for readability).
Thank you!
Following code will be helpful to you,
$('#quiz').on('submit',function(){
var score = parseInt($('input[name=question1]:checked').val())+
parseInt($('input[name=question2]:checked').val())+
parseInt($('input[name=question3]:checked').val());
alert('submit'+score);
//score can be assigned to any field you need
//$('#maturityLevel').val(score);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="quiz" method="post" name="quiz" action="url">
<label for="field1">Question 1</label>
<label><input name="question1" value="1" type="radio">Answer 1</label>
<label><input name="question1" value="4" type="radio">Answer 2</label>
<label><input name="question1" value="9" type="radio">Answer 3</label>
<label for="field2">Question 2</label>
<label><input name="question2" value="1" type="radio">Answer 1</label>
<label><input name="question2" value="4" type="radio">Answer 2</label>
<label><input name="question2" value="9" type="radio">Answer 3</label>
<label for="field3">Question 3</label>
<label><input name="question3" value="1" type="radio">Answer 1</label>
<label><input name="question3" value="4" type="radio">Answer 2</label>
<label><input name="question3" value="9" type="radio">Answer 3</label>
<input value="See your Results" type="submit">
</form>
Make sure to answer all the 3 question. Otherwise you have to do the proper validations before parsing using parseInt.
I my trying to make multiple choice quiz but for some reason when i click on the sumbit button at the end of the quiz nothing is appearing in the score input. Ive tried everything and still cant get it to work. Could someone please explain what im doing wrong? thanks
function checkAnswer() {
var correct = 0;
var q1 = document.quiz.q1.value;
var q2 = document.quiz.q2.value;
var q3 = document.quiz.q1.value;
var q4 = document.quiz.q4.value;
var answers["Cascading Style Sheets","Dynamic HTML","Netscape","Common Gateway Interface"];
if (q1 === answers[0]) {
correct++
}
if (q2 === answers[1]) {
correct++
}
if (q3 === answers[2]) {
correct++
}
if (q4 === answers[3]) {
correct++
}
var score = Math.round(correct / 4 * 100)
document.getElementById("score").innerHTML = score;
}
HTML:
<h3>Web Design Quiz</h3>
<form id="quiz" name="quiz">
<p> What does CSS stand for? </p>
<ul style="margin-top: 1pt">
<li>
<input type="radio" name="q1" value="Colorful Style Symbols">Colorful Style Symbols</li>
<li>
<input type="radio" name="q1" value="Cascading Style Sheets">Cascading Style Sheets</li>
<li>
<input type="radio" name="q1" value="Computer Style Symbols">Computer Style Symbols</li>
</ul>
2.
<p>What does DHTML stand for?</p>
<ul style="margin-top: 1pt">
<li>
<input type="radio" id="myCheck" name="q2" value="Dramatic HTML">Dramatic HTML</li>
<li>
<input type="radio" id="myCheck" name="q2" value="Design HTML">Design HTML</li>
<li>
<input type="radio" id="myCheck" name="q2" value="Dynamic HTML">Dynamic HTML</li>
</ul>
3.
<p>Who created Javascript?</p>
<ul style="margin-top: 1pt">
<li>
<input type="radio" id="myCheck" name="q3" value="Microsoft">Microsoft</li>
<li>
<input type="radio" id="myCheck" name="q3" value="Netscape">Netscape</li>
<li>
<input type="radio" id="myCheck" name="q3" value="Sun Micro Systems">Sun Micro Systems</li>
</ul>
4.
<p> What does CGI stand for?</p>
<ul style="margin-top: 1pt">
<li>
<input type="radio" id="myCheck" name="q4" value="Cascading Gate Interaction">Cascading Gate Interaction</li>
<li>
<input type="radio" id="myCheck" name="q4" value="Common GIF Interface">Common GIF Interface</li>
<li>
<input type="radio" id="myCheck" name="q4" value="Common Gateway Interface">Common Gateway Interface</li>
</ul>
<button type="button" onclick='checkAnswer()'>Submit </button>
<input type="reset" value="Clear answers">
<p>
Score = <input type=text size=15 id="score" name="percentage"><br>
</p>
<br>
Open the Developer Tools in your browser. Look at the Console.
You will see a ReferenceError because answers hasn't been defined anywhere.
Use a validator. You have two elements with the same ID.
You seem to be trying to set the innerHTML of a paragraph, but when browsers attempt to recover from your error, they will take the first element with that ID, which is an <input>.
You are triggering the JS when a submit button is clicked. As soon as the JS finished, the form will submit an a new page will be loaded.
Use a type="button".
When setting the value of an input-element you should use the value attribute of the element, rather than the innerHTML.
document.getElementById("score").value = score;
Edit
It is unclear whether you want to set the score in the paragraph element or in the input element, which both share the same id.
You have a lot of mistake in your code. Which were mention before in comments. Here's solution:
<h3>Web Design Quiz</h3>
<form id="quiz" name="quiz">
<p> What does CSS stand for? </p>
<ul style="margin-top: 1pt">
<li><input type="radio" name="q1" value="Colorful Style Symbols">Colorful Style Symbols</li>
<li><input type="radio" name="q1" value="Cascading Style Sheets">Cascading Style Sheets</li>
<li><input type="radio" name="q1" value="Computer Style Symbols">Computer Style Symbols</li>
</ul>
2. <p>What does DHTML stand for?</p>
<ul style="margin-top: 1pt">
<li><input type="radio" name="q2" value="Dramatic HTML">Dramatic HTML</li>
<li><input type="radio" name="q2" value="Design HTML">Design HTML</li>
<li><input type="radio" name="q2" value="Dynamic HTML">Dynamic HTML</li>
</ul>
3. <p>Who created Javascript?</p>
<ul style="margin-top: 1pt">
<li><input type="radio" name="q3" value="Microsoft">Microsoft</li>
<li><input type="radio" name="q3" value="Netscape">Netscape</li>
<li><input type="radio" name="q3" value="Sun Micro Systems">Sun Micro Systems</li>
</ul>
4.<p> What does CGI stand for?</p>
<ul style="margin-top: 1pt">
<li><input type="radio" name="q4" value="Cascading Gate Interaction">Cascading Gate Interaction</li>
<li><input type="radio" name="q4" value="Common GIF Interface">Common GIF Interface</li>
<li><input type="radio" name="q4" value="Common Gateway Interface">Common Gateway Interface</li>
</ul>
<input type="button" onclick='checkAnswer()'>check </input>
<input type="reset" value="Clear answers">
And in your js file
var answers = ["Cascading Style Sheets","Dynamic HTML","Netscape","Common Gateway Interface"];
My HTML
<div class="questions">
<p>Q1</p>
<label><input name="q1" id="q1-a" type="radio" />Q1 ans A</label>
<label><input name="q1" id="q1-b" type="radio" />Q1 ans B</label>
<label><input name="q1" id="q1-c" type="radio" />Q1 ans C</label>
</div>
<div class="questions hide">
<p>Q2</p>
<label><input name="q2" id="q1-a" type="radio" />Q2 ans A</label>
<label><input name="q2" id="q1-b" type="radio" />Q2 ans B</label>
<label><input name="q2" id="q1-c" type="radio" />Q2 ans C</label>
</div>
<div class="questions hide">
<p>Q3</p>
<label><input name="q3" id="q1-a" type="radio" />Q3 ans A</label>
<label><input name="q3" id="q1-b" type="radio" />Q3 ans B</label>
<label><input name="q3" id="q1-c" type="radio" />Q3 ans C</label>
</div>
Check
MY JS
$("#checkAns").click(function(){
}
Here are the array of answer which I want to compare
answers: { q1: 'a', q2: 'b', q3: 'a'}
If user trigger radio button then it will show alert if is Correct or Wrong then it will return true; if wrong false then this is the time it will show another question for answering
I do want to avoid if else in checking the user answer is this possible?
First, don't forget to add value on each radio button. Also id is not really needed here, except you need to do something on each radio button:
<div>
<label><input name="q1" type="radio" value="a" />Q1 A</label>
<label><input name="q1" type="radio" value="b" />Q1 B</label>
<label><input name="q1" type="radio" value="c" />Q1 C</label>
</div>
Then for checking answers, you can use this:
var answers = {q1 : 'a', q2 : 'b', q3 : 'a'};
$('#checkAns').click(function(e) {
$.each(answers, function(question, answer) {
if($('input:radio[name="' + question + '"]:checked').val() == answer)
alert(question + ': True');
else
alert(question + ': False!');
});
e.preventDefault();
});
Updated answer :
HTML & CSS
I think you don't need an anchor to click, because this time the script check the answer as soon as the radio button is triggered.
<style type="text/css">
.hide { display:none; }
</style>
<div class="questions">
<p>Q1</p>
<label><input type="radio" name="q1" value="a" />Q1 A</label>
<label><input type="radio" name="q1" value="b" />Q1 B</label>
<label><input type="radio" name="q1" value="c" />Q1 C</label>
</div>
<div class="questions hide">
<p>Q2</p>
<label><input type="radio" name="q2" value="a" />Q2 A</label>
<label><input type="radio" name="q2" value="b" />Q2 B</label>
<label><input type="radio" name="q2" value="c" />Q2 C</label>
</div>
<div class="questions hide">
<p>Q3</p>
<label><input type="radio" name="q3" value="a" />Q3 A</label>
<label><input type="radio" name="q3" value="b" />Q3 B</label>
<label><input type="radio" name="q3" value="c" />Q3 C</label>
</div>
Javascript using jQuery
var answers = {q1: 'a', q2: 'b', q3: 'a'};
$('input:radio').click(function() {
var container = $(this).parents('div');
var question = $(this).attr('name');
var answer = $(this).val();
alert(answers[question] == answer);
container.addClass('hide');
container.next().removeClass('hide');
});
Just modify the script as you need. Hope this time is right.. :P