jQuery Quiz compare correct answer in array - javascript

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

Related

How do I know if a user has selected an option in a form in html + javascript

I am trying to build a quiz with questions and options but I don't know how to add the options to the quiz. Also, I want to know if I selected the correct option and if the number of correct answers is shown at the end. Can someone help me build this?
I have tried adding options but I can't get the output needed.
<form align="center" id = "test">
Question 1: <input type="radio" name="radiogroup1" value="radio" id="radiogroup1"> Option 1
<input type="radio" name="radiogroup1" value="radio" id="radiogroup2"> Option 2 <br><be>
</form>
See if this helps you: (just an example to get the idea)
function submitAnswers() {
var total = 5;
var score = 0;
//Get user input
var q1 = document.forms["quizForm"]["q1"].value;
var q2 = document.forms["quizForm"]["q2"].value;
var q3 = document.forms["quizForm"]["q3"].value;
var q4 = document.forms["quizForm"]["q4"].value;
var q5 = document.forms["quizForm"]["q5"].value;
// Validation
for (var i = 1; i <= total; i++) {
if (eval('q' + i) == null || eval('q' + i) == '') {
alert("you missed question " + i);
return false;
}
}
//set correct answers
var answers = ["b", "d", "c", "a", "b"]
//check answers
for (var i = 1; i <= total; i++) {
if (eval('q' + i) == answers[i - 1]) {
score++;
}
}
alert('You scored ' + score + " out of " + total);
return false;
}
<div class="container">
<section>
<form name="quizForm" onsubmit="submitAnswers(); return false">
<h3>1. Question number one?</h3>
<input type="radio" name="q1" value="a" id="q1a"> a. answer11<br>
<input type="radio" name="q1" value="b" id="q1b"> b. answer12<br>
<input type="radio" name="q1" value="c" id="q1c"> c. answer13<br>
<input type="radio" name="q1" value="d" id="q1d"> d. answer14<br>
<h3>2. Question number two?</h3>
<input type="radio" name="q2" value="a" id="q2a"> a. answer21<br>
<input type="radio" name="q2" value="b" id="q2b"> b. answer22<br>
<input type="radio" name="q2" value="c" id="q2c"> c. answer23<br>
<input type="radio" name="q2" value="d" id="q2d"> d. answer24<br>
<h3>3. Question number three?</h3>
<input type="radio" name="q3" value="a" id="q3a"> a. answer31<br>
<input type="radio" name="q3" value="b" id="q3b"> b. answer32<br>
<input type="radio" name="q3" value="c" id="q3c"> c. answer33<br>
<input type="radio" name="q3" value="d" id="q3d"> d. answer34<br>
<h3>4. Question number four ?</h3>
<input type="radio" name="q4" value="a" id="q4a"> a. answer41<br>
<input type="radio" name="q4" value="b" id="q4b"> b. answer42<br>
<input type="radio" name="q4" value="c" id="q4c"> c. answer43<br>
<input type="radio" name="q4" value="d" id="q4d"> d. answer44<br>
<h3>5. Question number five ?</h3>
<input type="radio" name="q5" value="a" id="q5a">a. answer51<br>
<input type="radio" name="q5" value="b" id="q5b">b. answer52<br>
<br><br>
<input type="submit" value="Submit Answers">
</form>
</section>
</div>

Why does handleChange not fire correctly in react.js?

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.

How to execute the same code on each of the radio buttons with the same value

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

Adding form field values together into hidden field on form submit (js or jquery)

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.

JavaScript Quiz Valadition

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

Categories

Resources