How to show different links when certain questions are answered - javascript

How do I make it so that when I click AT&T, 8GB, and Black it shows a link and when I click Other, 8GB, and White it shows a different link. This is what I came up with. This is my first ever attempt so don't be rough on me. I'm trying to achieve something similar to http://glyde.com/sell/iphone-4s.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
<!--
.bgclr {background-color: white; color: black; font-weight: bold;}
-->
</style>
<script language="JavaScript">
<!-- Begin
var numQues = 3;
var numChoi = 3;
var answers = new Array(3);
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
</script>
</head>
<body>
<form name="quiz">
What carrier do you have?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q1" value="AT&T"/>AT&T</li>
<li><input type="radio" name="q1" value="Other"/>Other</li>
<li><input type="radio" name="q1" value="Unlocked"/>Unlocked</li>
</ul>
What is your phones capicity?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q2" value="8GB"/>8GB</li>
<li><input type="radio" name="q2" value="16GB"/>16GB</li>
</ul>
What color is your phone?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q3" value="Black"/>Black</li>
<li><input type="radio" name="q3" value="White"/>White</li>
</ul>
<input type="button" value="Get score" onClick="getScore(this.form)"/>
</body>
</html>
http://jsfiddle.net/XwN2L/2547/

OK. Add an "onclick" event to each element of the form, which calls a method called tryToMakeLink(). So for every element
<input type="radio" name="q1" value="AT&T"/>
should now read
<input type="radio" onclick=tryToMakeLink(); name="q1" value="AT&T"/>
Also, add a div to the bottom to display the dynamic link.
<form name="quiz" id='quiz'>
What carrier do you have?
<ul style="margin-top: 1pt">
<li><input type="radio" onclick=tryToMakeLink(); name="q1" value="AT&T"/>AT&T</li>
<li><input type="radio" onclick=tryToMakeLink(); name="q1" value="Other"/>Other</li>
<li><input type="radio" onclick=tryToMakeLink(); name="q1" value="Unlocked"/>Unlocked</li>
</ul>
What is your phones capicity?
<ul style="margin-top: 1pt">
<li><input type="radio" onclick=tryToMakeLink(); name="q2" value="8GB"/>8GB</li>
<li><input type="radio" onclick=tryToMakeLink(); name="q2" value="16GB"/>16GB</li>
</ul>
What color is your phone?
<ul style="margin-top: 1pt">
<li><input type="radio" onclick=tryToMakeLink(); name="q3" value="Black"/>Black</li>
<li><input type="radio" onclick=tryToMakeLink(); name="q3" value="White"/>White</li>
</ul>
<input type="button" value="Get score" onClick="getScore(this.form)"/>
<br>
<div id=linkDiv>
--
</div>
</form>
The tryToMakeLink() method does the following:
Look at each radio. If the user has not made a choice for each question, do nothing.
If the user has made a choice for each question, then show 1 link if they have 8gb at&t black, show another link if they have other 8gb white, show a 3rd link if they have any other combination. you can easily add other configurations by adding more else if clauses to the function.
So here it is (JavaScript)
function tryToMakeLink()
{
//get all selected radios
var q1=document.querySelector('input[name="q1"]:checked');
var q2=document.querySelector('input[name="q2"]:checked');
var q3=document.querySelector('input[name="q3"]:checked');
//make sure the user has selected all 3
if (q1==null || q2==null ||q3==null)
{
document.getElementById("linkDiv").innerHTML="--";
}
else
{
//now we know we have 3 radios, so get their values
q1=q1.value;
q2=q2.value;
q3=q3.value;
//now check the values to display a different link for the desired configuration
if (q1=="AT&T" && q2=="8GB" && q3=="Black")
{
document.getElementById("linkDiv").innerHTML="<a href=#>att 8gb black</a>";
}
else if (q1=="Other" && q2=="8GB" && q3=="White")
{
document.getElementById("linkDiv").innerHTML="<a href=#>other 8b white</a>";
}
else
{
document.getElementById("linkDiv").innerHTML="<a href=#>some third option</a>";
}
}
}
This is all javascript, as indicated by your post; however you may want to look into jQuery.
EDIT:
A better way to do this is to bind the click event to each radio when the document loads, instead of needing an "onclick=" in each input tag.
so you add an onload to your body
<body onLoad="attachClickEvents();">
and add this javascript
function attachClickEvents()
{
var inputs=document.getElementById('quiz').elements;
for (var i=0;i<inputs.length;i++)
{
inputs[i].onclick = function() {
tryToMakeLink();
};
}
}

I think that this could help you!
How to change the images on button click
It is another SO question that I found useful for the same thing!

Related

Disable button if radio is unchecked. Enable when checked

I can't seem to get my button to re-enable after it's been disabled. Currently, if nothing is checked and I mouseover it, the button disables. It stays enabled if I have something checked, but if I first hover over then button, with nothing checked, I can't get it to re-enable if I check something.
Here's My JS:
var inputs = document.getElementsByTagName('input');
var letsCookButton = document.querySelector('#letsCook');
letsCookButton.addEventListener('mouseover', checkIfChecked);
function checkIfChecked() {
letsCookButton.disabled = true;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
letsCookButton.disabled = false;
}
}
}
Here's my HTML:
div class="mainBox" id="box-one">
<p id="left-box-title">What are you looking for?<span>*</span></p>
<ul>
<li><input type="radio" name="food" id="side-food"> Side</li>
<li><input type="radio" name="food" id="main-food"> Main Dish</li>
<li><input type="radio" name="food" id="dessert-food"> Dessert</li>
<li><input type="radio" name="food" id="entire-meal"> Entire Meal</li>
</ul>
<button id="letsCook">LET'S COOK!</button>
</div>
You will have to slightly rethink how you want the UX of your app to work, because disabled elements do not produce events.
Since at least one radio button will remain checked after the first click, I would suggest disabling the button from the start and then enabling it on a radio click event.
<div class="mainBox" id="box-one">
<p id="left-box-title">What are you looking for?<span>*</span></p>
<ul id="radio-group">
<li><input type="radio" name="food" id="side-food"> Side</li>
<li><input type="radio" name="food" id="main-food"> Main Dish</li>
<li><input type="radio" name="food" id="dessert-food"> Dessert</li>
<li><input type="radio" name="food" id="entire-meal"> Entire Meal</li>
</ul>
<button id="letsCook" disabled>LET'S COOK!</button>
</div>
var inputGroup = document.querySelector('#radio-group');
var letsCookButton = document.querySelector('#letsCook');
inputGroup.addEventListener('click', function () {
letsCookButton.removeAttribute('disabled')
});
Working example in JS Fiddle: https://jsfiddle.net/Ollie1700/wxn9f63p/4/

My javascript quiz is not showing the results after submitting

I'm playing around with a javascript quiz but I'm having trouble showing the results. I would like the user to see the correct results when the user clicks on "Submit Answers" but nothing happens.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title> Simple JavaScript Quiz </title>
<link rel="stylesheet" href="css/style.css">
<script src="js/script.js"> </script>
</head>
<body>
<div id="container">
<header>
<h1> Simple JavaScript Quiz</h1>
<p> Test your knowledge in <strong>JavaScript fundamentals</strong></p>
</header>
<section>
<div id="results"> </div>
<form name="quizForm" onsubmit="return submitAnswers()">
<h3>1. In which elements do we put in JavaScript code?</h3>
<img src="scam.png" alt="Italian Trulli">
<input type="radio" name="q1" value="a" id="q1a">a. <js><br>
<input type="radio" name="q1" value="b" id="q1b">b. <script><br>
<input type="radio" name="q1" value="c" id="q1c">c. <body><br>
<input type="radio" name="q1" value="d" id="q1d">d. <link><br>
<h3>2. Which HTML attribute is used to reference an external JavaScript file?</h3>
<input type="radio" name="q2" value="a" id="q2a">a. src<br>
<input type="radio" name="q2" value="b" id="q2b">b. rel<br>
<input type="radio" name="q2" value="c" id="q2c">c. type<br>
<input type="radio" name="q2" value="d" id="q2d">d. href<br>
<h3>3. How would you write "Hello" in an alert box?</h3>
<input type="radio" name="q3" value="a" id="q3a">a. msg("Hello");<br>
<input type="radio" name="q3" value="b" id="q3b">b. alertBox("Hello");<br>
<input type="radio" name="q3" value="c" id="q3c">c. document.write("Hello");<br>
<input type="radio" name="q3" value="d" id="q3d">d. alert("Hello");<br>
<input type="submit" value="Submit Answers"> <br><br>
</form>
</section>
</div>
</body>
</html>
And this is my javascript code:
function submitAnswers() {
var total = 3;
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;
// set correct answers
var answers = ['b', 'a', 'd'];
// check answers (note i - 1 to account for array starting with [0])
for (var i = 1; i <= total; i++) {
if (eval("q" + i) == answers[i - 1]) {
score++;
}
}
// display results
var results = document.getElementById("results");
results.innerHTML ='<h3>You Scored <span> '+score+' </span> out of <span>'+total+'</span> </h3>';
alert('You Scored '+score+' out of '+total);
}
After I click "Submit Answers" nothing happens. Any ideas?
Instead of adding onsubmit property directly in form element, add submit event listener on it and prevent the event from default behavior. Default behavior of submitig a form is refreshing whole page.
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
submitAnswers();
})

Javascript execution engine with getElementsByClassName

Sorry for the stupid question and the indentation of the code source below. I am completely new to coding. Could someone help me understand why I need to click on the submit button twice to see the second correct answer turn green as per the code below? Worse, when I insert an 'alert' method into the script, the first correct answer turns green only after I click on the 'OK' of the alert window.
Thank you very much
Ehoussoud
function check() {
var cans = document.getElementsByClassName('correct');
for (i = 0; i < cans.length; i++) {
cans[i].className = "cool";
}
}
form {
font-size: 16px;
font-family: Verdana;
}
.cool {
color: lightgreen;
}
<body>
<h1>Premier League 2017/18 Quiz</h1>
<form>
<p>Q1.Which of the three championship teams were promoted to the premier league?
</p><br>
<div class="correct"> <input type="radio" name="Q1" value="A">Wolves,Cardiff,Fulham </div>
<input type="radio" name="Q1" value="B">Wolves,Middlesbrough,Aston Villa
</br>
<p>Q2.Which player made the most assists?<br></p>
<input type="radio" name="Q2" value="A">David Silva</br>
<div class="correct"><input type="radio" name="Q2" value="B">Kevin De Bruyne
</div>
</br>
<input type="button" value="submit" onclick="check()">
</form>
</body>
Using jquery could save you some time when you are working with multiple elements with the same id/class. You were using element.className = "class-name"; You should use element.classList.add("class-name"); like so:
function check(){
var cans=document.getElementsByClassName('correct');
for(i=0;i<cans.length;i++){
cans[i].classList.add("cool");
}
}
Hope this helps!
The problem is that in the first iteration you are renaming one the elements with class correct. So, it you had two elements with this class (How is the case) in the second iteration cans[i] (i = 1) will not exists because cans just have one element. So for that i access cans[0] because it's all going to exists.
function check() {
var cans = document.getElementsByClassName('correct');
var quantity = cans.length;
for (i = 0; i < quantity; i++) {
cans[0].className = "cool";
}
}
form {
font-size: 16px;
font-family: Verdana;
}
.cool {
color: lightgreen;
}
<body>
<h1>Premier League 2017/18 Quiz</h1>
<form>
<p>Q1.Which of the three championship teams were promoted to the premier league?
</p><br>
<div class="correct"> <input type="radio" name="Q1" value="A">Wolves,Cardiff,Fulham </div>
<input type="radio" name="Q1" value="B">Wolves,Middlesbrough,Aston Villa
</br>
<p>Q2.Which player made the most assists?<br></p>
<input type="radio" name="Q2" value="A">David Silva</br>
<div class="correct"><input type="radio" name="Q2" value="B">Kevin De Bruyne
</div>
</br>
<input type="button" value="submit" onclick="check()">
</form>
</body>

Jquery radio button check causing form to work incorrectly

I have a radio form questionnaire that should when the user submits their results take them to a specific page. However since adding the code to make sure that all the radio buttons have to be checked before the user can submit the code acts incorrectly, always taking the user to one specific page (the last in the below if statement (software.html).
This is the code for the html questionnaire
<form id="quiz">
<!-- Question 1 -->
<h2>Do you enjoy fixing things</h2>
<!-- Here are the choices for the first question. Each input tag must have the same name. For this question, the name is q1. -->
<!-- The value is which answer the choice corresponds to. -->
<div class="questionsWrap">
<label><input type="radio" name="q1" id="q1" value="c1">
Yes
</label><br />
<label><input type="radio" name="q1" id="q1" value="c2">
No
</label><br />
<label><input type="radio" name="q1" id="q1" value="c3">
Maybe
</label><br />
</div>
<div class="questionsWrap">
<!-- Question 2 -->
<h2>Do you enjoy problem solving?</h2>
<!-- Here are the choices for the second question. Notice how each input tag has the same name (q2), but a different name than the previous question. -->
<label><input type="radio" name="q2" value="c2">
Yes
</label><br />
<label><input type="radio" name="q2" value="c1">
No
</label><br />
<label><input type="radio" name="q2" value="c3">
Unsure
</label><br />
</div>
<div class="questions">
<!-- Question 3 -->
<h2>Do you enjoy maths?</h2>
<!-- Choices for the third question -->
<label><input type="radio" name="q3" value="c2">
Yes
</label><br />
<label><input type="radio" name="q3" value="c1">
No
</label><br />
<label><input type="radio" name="q3" value="c3">
Unsure
</label><br />
</div>
<div class="questions">
<!-- Question 4 -->
<h2>Do you often take thing apart to rebuild them?</h2>
<!-- Choices for the fourth question -->
<label><input type="radio" name="q4" value="c1">
Yes
</label><br />
<label><input type="radio" name="q4" value="c2">
No
</label><br />
<label><input type="radio" name="q4" value="c3">
I have never done it before so i don't know
</label><br />
</div>
<div class="questions">
<!--Question 5 -->
<h2>Hardware or Software?</h2>
<label><input type="radio" name="q5" value="c1">
Hardware</label><br />
<label><input type="radio" name="q5" value="c2">
Software</label><br />
</div>
<button type='button' id="submit" onclick="answers()">Submit Your Answers</button>
<button type="reset" id="reset" onclick="resetAnswer()">Reset</button>
</form>
This is the code that calculates the questionnaire result
<script>
function answers(){
// initialize variables for each choice's score
// If you add more choices and outcomes, you must add another variable here.
var c1score = 0;
var c2score = 0;
var c3score = 0;
// get a list of the radio inputs on the page
var choices = document.getElementsByTagName('input');
// loop through all the radio inputs
for (i=0; i<choices.length; i++) {
// if the radio is checked..
if (choices[i].checked) {
// add 1 to that choice's score
if (choices[i].value == 'c1') {
c1score = c1score + 1;
}
if (choices[i].value == 'c2') {
c2score = c2score + 1;
}
if (choices[i].value == 'c3') {
c3score = c3score + 1;
}
// If you add more choices and outcomes, you must add another if statement below.
}
}
// Find out which choice got the highest score.
// If you add more choices and outcomes, you must add the variable here.
var maxscore = Math.max(c1score,c2score,c3score);
// Display answer corresponding to that choice
var answerbox = document.getElementById('answer');
if (c1score == maxscore) { // If user chooses the first choice the most, this outcome will be displayed.
window.location.href='Hardware.html';
}
if (c2score == maxscore) { // If user chooses the second choice the most, this outcome will be displayed.
window.location.href='Software.html';
}
/* if (c3score == maxscore) { // If user chooses the third choice the most, this outcome will be displayed.
alert("no third career sector page currently exists in this version");
window.location.href='questionnaire1.html';
}
*/
// If you add more choices, you must add another response below.
}
</script>
This is the code that causes the issue, it should stop the user from submitting the form if not all the radio buttons have been submitted.
<script>
$(function(){
$('button[type=button]').click(function(){
var all_answered = true;
$(':radio').each(function(){
if($(':radio[name='+$(this).attr('name')+']:checked').length == 0)
{
all_answered = false;
}
});
alert(all_answered);
});
});
</script>

What's the best way to display new divs whenever a radio button is selected?

<div id="q1">
<p>1. are you a human?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Male</label><br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Female</label><br/>
</ul>
</div>
<div id="q2" style="display: none;">
<p>2.what's your favorite color out of these listed</p>
<ul class="answers">
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">Pink</label><br/>
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">Blue</label><br/>
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">Greem</label><br/>
</ul>
</div>
document.getElementById('q1a').onclick = function() {
document.getElementById("q2").style.display = "block";
}
document.getElementById('q1b').onclick = function() {
document.getElementById("q2").style.display = "block";
}
document.getElementById('q2a').onclick = function() {
document.getElementById("q3").style.display = "block";
}
document.getElementById('q2b').onclick = function() {
document.getElementById("q3").style.display = "block";
}
document.getElementById('q2c').onclick = function() {
document.getElementById("q3").style.display = "block";
}
So right now i'm basically checking to see if the user is checking a radio button inside of their divs and if they button is checked then the next div will be displayed.
However, this method seems kind of inefficient to me but I can't really think of a better way to do this.
You could use a data attribute to declare what the next question is and then query that to set visibility. Something like:
document.addEventListener('click', function(e) {
if (e.target.dataset.next) {
document.getElementById(e.target.dataset.next).classList.add('visible');
}
});
.question {
display: none;
}
.question.visible {
display: block;
}
<div id="q1">
<p>1. are you a human?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a" data-next="q2"><label for="q1a">Male</label><br/>
<input type="radio" name="q1" value="b" id="q1b" data-next="q2"><label for="q1b">Female</label><br/>
</ul>
</div>
<div id="q2" class="question">
<p>2.what's your favorite color out of these listed</p>
<ul class="answers">
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">Pink</label><br/>
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">Blue</label><br/>
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">Greem</label><br/>
</ul>
</div>
You can target the input elements by their "name" then with the radio name array, you can write some function like this one;
function radioValue(radioName){
var radioArray = document.getElementsByName(radioName);
var i = 0;
while(i < radioArray.length){
if(radioArray[i].checked){
return radioArray[i].value;
break;
}
i++;
}
}
This function takes the name of the input[radio] elements and checks one by one if they are "checked" then returns the checked inputs' value.
You can use it as for your radio series;
document.addEventListener('click', function(){
//console.log(radioValue("radioName"));
document.getElementById("div-"+radioValue("radioName")).display = "block";
});
Read more about getElementsByName: http://www.w3schools.com/jsref/met_doc_getelementsbyname.asp

Categories

Resources