How to create a single-question quiz in React? - javascript

How do I implement the logic for correct and incorrect answers? I have created a single-question quiz with multiple options. I have created a Quiz component. Here is the source:
Quiz Component
export default function Quiz(props) {
return (
<div className="QuizContainer">
<div className="quizHeader">
<h1>Question</h1>
<p className="PracticeDescription">
Read the question and choose the most correct option.
</p>
</div>
<hr/>
<div className="PracticeQuestionContainer">
<p>{props.question}</p>
<div class="option-container">
<input type="radio" name="select" id="option-1" className="input-radio" />
<input type="radio" name="select" id="option-2" className="input-radio" />
<input type="radio" name="select" id="option-3" className="input-radio" />
<input type="radio" name="select" id="option-4" className="input-radio" />
<label for="option-1" className="option option-1">
<div className="dot"></div>
<span>{props.option1}</span>
</label>
<label for="option-2" className="option option-2">
<div className="dot"></div>
<span>{props.option2}</span>
</label>
<label for="option-3" className="option option-3">
<div className="dot"></div>
<span>{props.option3}</span>
</label>
<label for="option-4" className="option option-4">
<div className="dot"></div>
<span>{props.option4}</span>
</label>
</div>
</div>
</div>
);
}
And I have used this component on the page like this:
<Quiz
question="1. Which one is not a JavaScript variable?"
option1="var a=5"
option2="let b=6"
option3="const c=3"
option4="int x=9"
/>
Here how it looks like:
If the user selects the correct answer, it should colsole.log("Correct!") else console.log("Incorrect!"). How do I do this? Please help me!!

First of all you'd also need to pass a correct answer to your Quiz component, after which you'd need to take a look at event handling, so whenever user clicks an option, a function gets called which compares clicked answer with the correct answer.
Read more here: https://reactjs.org/docs/handling-events.html

Related

Returning Javascript Response from Conditional Logic as an Answer to HTML Quiz Input on the Same Page without Refresh or Navigating Away

Beginner here! I'm coding a quiz website that takes in 10+ questions and returns a response to the user after receiving a combination of their answers. I included a much abbreviated version of the code below with placeholder text to help illustrate the issue.
The HTML form has a radio input which is related to javascript variables in a separate linked JS file in a onsubmit function called answers(). There are no correct/incorrect responses, only 50+ unique responses depending on the user input combo. The function declares the answer to each question using let, then 50+ conditional logic statements pass the answer variables to get a result.
Thankfully the quiz works! It successfully returns the correct unique response after a user inputs and submits. The only problem is I want to answer to display in a container at the bottom of the page onsubmit, and instead it sends it to a new page where the text is isolated without styling or context and navigates away from the quiz page. I am returning the result to the user with a document.write() method, but I've also tried document.getElementById('id').innerHTML = result and the .textContent method as well. The innerHTML and textContent methods have returned nothing, and the document.write will only return the result on a separate page.
Does anyone know how I can return the unique result as a response to the user at the bottom of the webpage after the quiz? I want it to be in a container that is hidden until the quiz is submitted and it appears and is populated with the result after they press submit. I am new to coding, so I greatly appreciate any and all help! Thank you! :)
let commentLine2 = "Hello world!";
function answers()
{
let Answer_Q2 = document.querySelector('input[name="Answer_Q2"]:checked').value;
let Answer_Q3 = document.querySelector('input[name="Answer_Q3"]:checked').value;
let Answer_Q4 = document.querySelector('input[name="Answer_Q4"]:checked').value;
if (Answer_Q3 == "No" && Answer_Q4 == "No"){
document.write(commentLine2);};
}
<form onsubmit="answers();">
<div>
<fieldset>
<!--Question 1 textbox not considered in quiz results-->
<legend>Question 1: What's is your name?</legend>
<input type="text">
<legend>Grouping 1</legend>
<h3>Question 2: _______?</h3>
<div class="input-group mb-3">
<input type="radio" id="Option 1" name="Answer_Q2" value="Option 1" >
<label for="Option 1">Option 1</label><br>
<input type="radio" id="Option 2" name="Answer_Q2" value="Option 2" >
<label for="Option 2">Option 2</label><br>
<input type="radio" id="Option 3" name="Answer_Q2" value="Option 3" >
<label for="Option 3">Option 3</label><br>
<input type="radio" id="Option 4" name="Answer_Q2" value="Option 4" >
<label for="Option 4">Option 4</label><br>
<label class="input-group-text" for="Answer_Q2"></label>
</div>
<div>
<h3>Question 3: _______?</h3>
<div class="input-group mb-3">
<input type="radio" id="No" name="Answer_Q3" value="No">
<label for="No">No</label><br>
<input type="radio" id="Yes" name="Answer_Q3" value="Yes">
<label for="Yes">Yes</label><br>
<label class="input-group-text" for="Answer_Q3"></label>
</div>
</div>
</fieldset>
<fieldset>
<legend>Grouping 2</legend>
<h3>Question 4: ________?</h3>
<div class="input-group mb-3">
<input type="radio" id="Yes" name="Answer_Q4" value="Yes">
<label for="Yes">Yes</label><br>
<input type="radio" id="No" name="Answer_Q4" value="No">
<label for="No">No</label><br>
<label class="input-group-text" for="Answer_Q4"></label>
</div>
</fieldset>
<input type="Submit" id="btn-form" value="What's my result?">
</fieldset>
</form>
<fieldset class="answer-container">
<div>
<p id ="answer-Block"></p>
</div>
</fieldset>
if (Answer_Q3 == "No" && Answer_Q4 == "No"){
document.write(commentLine2);};
}
document.write(commentLine2) would overwrite everything in the page and replace it with the contents of commentLine2. instead you should select the output container #answer-Block and put the response there:
if (Answer_Q3 == "No" && Answer_Q4 == "No"){
let answerBlock = document.getElementById('answer-Block');
answerBlock.textContent = commentLine2;
}
it would also help if you triggered the function on click of the submit button instead of on submission of the form itself (if you're not sending it to a server backend anyway), so modify your html like so:
<form onsubmit="event.preventDefault()">
and then on the button like so:
<input type="Submit" onclick="answers()" id="btn-form" value="What's my result?">

Vue: How to display different images based on RadioButton choice

I am facing a problem where I want to display a different image if a radiobutton is selected with Vuejs. It currently only shows the image for the false state since I do not seem to be able to retrieve the state of the button in the way I tried. Here is an example with two buttons:
<template>
<div id="choose-route">
<label>
<input type="radio" name="Radio" id="choice1"
v-on:change="someMethodOne"
/>
<img
:src="checked ? 'icon_checked.png' : 'icon.png'"
/>
</label>
<label>
<input type="radio" name="Radio" id="choice2"
v-on:change="someMethodTwo"
/>
<img
:src="checked ? 'different_icon_checked.png' : 'different_icon.png'"
/>
</label>
</div>
</template>
<script>
export default {
methods: {
someMethodOne () {
// does something
},
someMethodTwo () {
// does another thing
}
}
}
</script>
<style>
</style>
How do I go about changing the image based on the checked state of the radiobutton? I already did it using CSS, but that lead to another problem due to the fact that I use recursive components which is why I am here now.
Use v-model. You can also use watch to do something when checked value change.
There is this exact example on Vue.js' website.
https://v2.vuejs.org/v2/guide/forms.html#Radio
new Vue({
el: "#app",
data: {
checked: null
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="radio" id="one" value='One' v-model="checked">
<label for="one">Option one</label>
<br>
<input type="radio" id="two" value="Two" v-model="checked">
<label for="two">Option two</label>
<br>
<span>Checked: {{ checked }}</span>
<br>
<span v-if="checked === 'One'">One is checked!</span>
<span v-else-if="checked === 'Two'">Two is checked!</span>
</div>

Check to see if radio buttons are dirty/touched in a reactive form

My StackBlitz example
I have built an Angular Reactive Form. On it I have 2 radio buttons, one selected by default(however in my example its not showing selected on the UI).
I have an ngIf div that should display if the radio button has changed or touched || Dirty, e.g
<div formGroupName="radioButtons" class="form-group col-6 pl-0 pt-3">
<div class="form-check-inline">
<label for="yes" class="col-12 customradio"
><span>yes</span>
<input value="yes" id="yes" type="radio" name="radiot" formControlName="radiot"/>
</label>
<label for="no" class="customradio"
><span>no</span>
<input value="no" id="no" type="radio" name="radiot" formControlName="radiot" />
</label>
</div>
<div class="form-check__related" *ngIf="radioButtons.radiot.touched">
DISPLAY ME
</div>
However, I cant get it to work and get
Error: Cannot read property 'radiot' of undefined
juts replace
*ngIf="radioButtons.radiot.touched"
with
*ngIf="form.controls.radioButtons.touched"
Your problem will be solved
https://stackblitz.com/edit/angular-pfctfu
juste add a getter method inside your ts which return the form group :
get radioButtons(){
return this.form.get('radioButtons') ;
}
inside your html
{{radioButtons.controls.radiot.touched}}

Indicate checkbox checked in angular

I have put together what I thought would be a very simple example of how I could fire off a function from a checkbox being checked in angular and have that function check to see the new value of the checkbox and accordingly display or not display a message. It works, but only after I have checked and unchecked the box at least once. For this reason I figured I simply would need to default the checkbox value to false and that would take care of the problem but it didn't. Can anyone help me tweak this to get it working and if so, maybe explain why my thinking is flawed, what do I not understand about the $scopes state. BTW it is also flipped, meaning that when I check the box the message goes away and when I uncheck it it says it's checked.
I am doing these exercises to get a better idea how angular works and I know deep down this is a javascript issue, but I still don't have it figured out. Any help is appreciated
app.js
var formApp = angular
.module('formApp', [])
.controller('formController', function($scope) {
$scope.formData = {};
$scope.redCheckFunction = function() {
if ($scope.formData.favoriteColors.red == true){
$scope.redMessage = "red is checked";
} else {
$scope.redMessage = "";
}
};
});
index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app and controller -->
<body ng-app="formApp" ng-controller="formController">
<div>
<h2>Angular Checkboxes</h2>
<form>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name"
ng-model="formData.name">
<label>Description</label>
<input type="text" class="form-control" name="description"
ng-model="formData.description">
</div>
<!-- MULTIPLE CHECKBOXES -->
<label>Favorite Colors</label>
<div class="form-group">
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors"
ng-model="formData.favoriteColors.red"
ng-init="favoriteColors.red.disabled=false"
ng-click="redCheckFunction()"> Red
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors"
ng-model="formData.favoriteColors.blue"> Blue
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors"
ng-model="formData.favoriteColors.green"> Green
</label>
</div>
<button type="submit" class="btn btn-danger btn-lg">Send Away!</button>
<h2>{{redMessage}}</h2>
</form>
<h2>Sample Form Object</h2>
<pre>
{{ formData }}
</pre>
</div>
</body>
</html>
I created a pen to make things easier:
Checkbox Pen
ng-click is fired before the model is updated:
Note that ngClick events will occur before the model is updated.
You need to use the ng-change directive:
Evaluate the given expression when the user changes the input.
http://codepen.io/anon/pen/azaJob
<label>Favorite Colors</label>
<div class="form-group">
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red" ng-init="formData.favoriteColors.red.disabled=false" ng-change="redCheckFunction()"> Red
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.blue"> Blue
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.green"> Green
</label>
</div>
When you enter the function redCheckFunction the value is already updated.

Delete drop down when it is blank using Javascript or Jquery

Is it possible to write a Javascript function to delete a drop down when it is blank?
<form name="myform" method="post" enctype="multipart/form-data" action="" id="myform">
<div>
<label id="question1">1) Draw recognizable shapes</label>
<br />
<input type="radio" value="Yes" id="question1_0" name="question1_0" />
Yes
<input type="radio" value="No" id="question1_1" name="question1_1" />
No
</div>
<div>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
<div>
<label id="question3">3) Hold a pencil</label>
<br />
<input type="radio" value="Yes" id="question3_0" name="question3_0" />
Yes
<input type="radio" value="No" id="question3_1" name="question3_1" />
No
</div>
<input type="submit" value="Delete Drop Down" onclick="return checkanddelete"/>
</form>
If somebody does not select question 2 for example, it deletes question 2 label and the drop down.
Assuming you actually meant radio button groups (and not drop down lists) then firstly your HTML is incorrect, you need to set the name values of each group of radio buttons to be the same:
<input type="radio" value="Yes" id="question1_0" name="question1" /> Yes
<input type="radio" value="No" id="question1_1" name="question1" /> No
Then you need to loop through the list of radio buttons, if none in the group are selected then delete the parent div:
$('input[type=submit]').on('click', function() {
var radioArr = [];
$(':radio').each(function(){
var radName = this.name;
if($.inArray(radName, radioArr) < 0 && $(':radio[name='+radName+']:checked').length == 0)
{
radioArr.push(radName);
$(this).closest("div")
.remove();
}
});
return false; //to stop the form submitting for testing purposes
});
While you are there, you might want to add some <label for=""> tags around your text.
Here is a jsFiddle of the solution.
If your dropdown has an id of DropDown, and you are looking to hide the dropdon on submit click:
function checkanddelete()
{
if ( $('#question2_0.=:checked, #question2_1:checked').length )
$('#dropdown').hide() // Or $('#dropdown').remove() if you do not plan on showing it again.
return false; // if you plan on not submitting the form..
}
Optimization for use in a module for a page include adding appropriate ids and classes to the divs, which I'm assuming that in full code are there, but if you are planning on making UI adjustments I would advise against using a submit button in the mix..
I don't know, what do you mean under "dropdown menu", but here some info, that can help you.
You can set a class name for the all Objects, you want to delete. E.g.
HTML
<div>
<label class='question2' id="question2">2) Competently cut paper </label>
<br />
<input class='question2' type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input class='question2' type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
JS
$(".question2").remove();
As an another solution you can set an ID for the DIV Tag above all of this elements
<div id='block_to_remove'>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
And then remove it in JS
$("#block_to_remove").remove();

Categories

Resources