issue with if/else conditions with radio elements - javascript

I'm not good with Javascript and I'm trying to build a two-question quiz based on yes-no answers. When I look at the console I see the yes-no values if I do console.log(answer1 + answer3); But the alert doesn't work. If I remove .checked and do equal to true/false the first alert works.
Any help would be appreciated
var answer1 = document.getElementById('q1').value;
var answer2 = document.getElementById('q2').value;
var answer3 = document.getElementById('q3').value;
var answer4 = document.getElementById('q4').value;
if (answer1.checked && answer3.checked) {
alert('walking park');
}
else if (answer1.checked && answer4.checked) {
alert('no walk in park');
}
else if (answer2.checked && answer4.checked ) {
alert('oh noooo!');
}
else if (answer2.checked && answer3.checked) {
alert('cor blimey gov!');
}
<form>
<p>Question 1</p>
<fieldset>
<label for="Question1">Can your dog eat food?</label>
<input type="radio" id="q1" name="question1" value="yes"> Yes<br>
<input type="radio" id="q2" name="question1" value="no"> No
</fieldset>
<p>Question 2</p>
<fieldset>
<label for="Question2">Can your dog run in the park</label>
<input type="radio" id="q3" name="question2" value="yes"> Yes<br>
<input type="radio" id="q4" name="question2" value="no"> No
</fieldset>
<button type="button" id="myBtn" class="btn btn-med btn-brand-one">submit</button>
</form>

Use checked == true or simply checked and remove .value
answer1 = document.getElementById('q1');
answer2 = document.getElementById('q2');
answer3 = document.getElementById('q3');
answer4 = document.getElementById('q4');
function checkanswear(event){
event.preventDefault()
if (answer1.checked && answer3.checked) {
alert('walking park');
}
else if (answer1.checked&& answer4.checked) {
alert('no walk in park');
}
else if (answer2.checked && answer4.checked ) {
alert('oh noooo!');
}
else if (answer2.checked && answer3.checked) {
alert('cor blimey gov!');
}
}
<form>
<p>Question 1</p>
<fieldset>
<label for="Question1">Can your dog eat food?</label>
<input type="radio" id="q1" name="question1" value="yes"> Yes<br>
<input type="radio" id="q2" name="question1" value="no"> No
</fieldset>
<p>Question 2</p>
<fieldset>
<label for="Question2">Can your dog run in the park</label>
<input type="radio" id="q3" name="question2" value="yes"> Yes<br>
<input type="radio" id="q4" name="question2" value="no"> No
</fieldset>
<button onclick="checkanswear(event)" id="myBtn" class="btn btn-med btn-brand-one">submit</button>
</form>

The problem is that the .value of your checkboxes is the string "yes" or "no". Strings don't have a checked attribute.
Solution: Just remove the .value part. Let answer1, answer2, etc be the input elements themselves. Then you can use .checked on them.
Example:
document.getElementById('myBtn').onclick = function() {
var answer1 = document.getElementById('q1');
var answer2 = document.getElementById('q2');
var answer3 = document.getElementById('q3');
var answer4 = document.getElementById('q4');
if (answer1.checked && answer3.checked) {
alert('walking park');
} else if (answer1.checked && answer4.checked) {
alert('no walk in park');
} else if (answer2.checked && answer4.checked) {
alert('oh noooo!');
} else if (answer2.checked && answer3.checked) {
alert('cor blimey gov!');
}
};
<form>
<p>Question 1</p>
<fieldset>
<label for="Question1">Can your dog eat food?</label>
<input type="radio" id="q1" name="question1" value="yes"> Yes<br>
<input type="radio" id="q2" name="question1" value="no"> No
</fieldset>
<p>Question 2</p>
<fieldset>
<label for="Question2">Can your dog run in the park</label>
<input type="radio" id="q3" name="question2" value="yes"> Yes<br>
<input type="radio" id="q4" name="question2" value="no"> No
</fieldset>
<button type="button" id="myBtn" class="btn btn-med btn-brand-one">submit</button>
</form>

Related

how do I fix the score in my option quiz?

I have a problem with the option quiz, more precisely with the evaluation of the correct answers. I don't get a score and it still stays at 0. Thank you for your help.
function check(){
var question1 = document.getElementsByClassName("question1")[0];
var question2 = document.getElementsByClassName("question2")[0];
var question3 = document.getElementsByClassName("question3")[0];
var correct = 0;
if (question1 == "Červená, Zelená, Modrá") {
correct++;
}
if (question2 == "0, 255") {
correct++;
}
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
<form id="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" id="mc" name="question1" value="Červená, Zelená, Modrá">Červená, Zelená, Modrá<br>
<input type="radio" id="mc" name="question1" value="Červená, Zelená, Žlutá">Červená, Zelená, Žlutá<br>
<input type="radio" id="mc" name="question1" value="Černá, Fialová, Modrá">Červená, Fialová, Modrá<br>
</form>
<br>
<form id="quiz">
<p style="font-weight: 900">RGB monitory jsou schopny regulovat jas na jaké stupnici?</p>
<input type="radio" id="mc" name="question2" value="0, 275">0, 275<br>
<input type="radio" id="mc" name="question2" value="0, 255">0, 255<br>
<input type="radio" id="mc" name="question2" value="50, 355">50, 355<br>
</form>
<br>
<form id="quiz">
<p style="font-weight: 900">Má každý bod určenou svou přesnou polohu?</p>
</form>
<br>
<input id="check-btn" type="button" value="Vyhodnotit test" onclick="check();">
<br>
<br>
<div id="number_correct"></div>
So, First, ids should unique. Remove all your id="mc".
Second. you need to get the value of the "Selected" option; Access using "input[name="question1"]:checked" and access value using "selectedOption.value".
See the snippet below:
function check(){
var question1 = document.querySelector('input[name="question1"]:checked');
var question2 = document.querySelector('input[name="question2"]:checked');
var question3 = document.querySelector('input[name="question3"]:checked');
var correct = 0;
if (question1 !=null && question1.value == "Červená, Zelená, Modrá") {
correct++;
}
if (question2 !=null && question2.value == "0, 255") {
correct++;
}
if (question3 !=null &&question3.value == "Ano") {
correct++;
}
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
<form id="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" name="question1" value="Červená, Zelená, Modrá">Červená, Zelená, Modrá<br>
<input type="radio" name="question1" value="Červená, Zelená, Žlutá">Červená, Zelená, Žlutá<br>
<input type="radio"name="question1" value="Černá, Fialová, Modrá">Červená, Fialová, Modrá<br>
</form>
<br>
<form id="quiz">
<p style="font-weight: 900">RGB monitory jsou schopny regulovat jas na jaké stupnici?</p>
<input type="radio" name="question2" value="0, 275">0, 275<br>
<input type="radio" name="question2" value="0, 255">0, 255<br>
<input type="radio" name="question2" value="50, 355">50, 355<br>
</form>
<br>
<form id="quiz">
<p style="font-weight: 900">Má každý bod určenou svou přesnou polohu?</p>
<input type="radio" name="question3" value="Někdy ano, někdy ne">Někdy ano, někdy ne<br>
<input type="radio" name="question3" value="Ne">Ne<br>
<input type="radio" name="question3" value="Ano">Ano<br>
</form>
<br>
<input id="check-btn" type="button" value="Vyhodnotit test" onclick="check();">
<br>
<br>
<div id="number_correct"></div>
you have a couple of issues:
id's have to be unique.
you didn't specify any classes in your html
you need to get the 'value' of the input
you need to reference the correct index
function check(){
var question1 = document.querySelector('input[name="question1"]:checked');
var question2 = document.querySelector('input[name="question2"]:checked');
var question3 = document.querySelector('input[name="question3"]:checked');
//console.log(question1,question2,question3)
var correct = 0;
if (question1 != null && question1.value == "Červená, Zelená, Modrá") {
correct++;
}
if (question2 != null && question2.value == "0, 255") {
correct++;
}
if (question3 != null && question3.value == "Ano") {
correct++;
}
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
<form id="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" class='question1' name="question1" value="Červená, Zelená, Modrá">Červená, Zelená, Modrá<br>
<input type="radio" class='question1' name="question1" value="Červená, Zelená, Žlutá">Červená, Zelená, Žlutá<br>
<input type="radio" class='question1' name="question1" value="Černá, Fialová, Modrá">Červená, Fialová, Modrá<br>
</form>
<br>
<form id="quiz">
<p style="font-weight: 900">RGB monitory jsou schopny regulovat jas na jaké stupnici?</p>
<input type="radio" class='question2' name="question2" value="0, 275">0, 275<br>
<input type="radio" class='question2' name="question2" value="0, 255">0, 255<br>
<input type="radio" class='question2' name="question2" value="50, 355">50, 355<br>
</form>
<br>
<form id="quiz">
<p style="font-weight: 900">Má každý bod určenou svou přesnou polohu?</p>
<input type="radio" class='question3' name="question3" value="Někdy ano, někdy ne">Někdy ano, někdy ne<br>
<input type="radio" class='question3' name="question3" value="Ne">Ne<br>
<input type="radio" class='question3' name="question3" value="Ano">Ano<br>
</form>
<br>
<input id="check-btn" type="button" value="Vyhodnotit test" onclick="check();">
<br>
<br>
<div id="number_correct"></div>

multiple choice quiz with class correct and wrong

I created a multiple choice quiz, and it working perfectly, I mean get the total score written on the website, but I wish to change it to just giving an extra 'correct' or 'wrong' CSS class to the selected input radio buttons after the Submit button has been hit.
HTML:
<section class="quiz">
<div id="results"></div>
<form name="quizForm" onsubmit="return submitAnswer()">
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 1</h4>
<p>Question 1</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q1" value="a" id="q1a"><label for="q1a">Test 1</label><br>
<input data-answer type="radio" name="q1" value="b" id="q1b"><label for="q1b">Test 2</label><br>
<input data-answer type="radio" name="q1" value="c" id="q1c"><label for="q1c">Test 3</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 2</h4>
<p>Question 2</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q2" value="a" id="q2a"><label for="q2a">Test 4</label><br>
<input data-answer type="radio" name="q2" value="b" id="q2b"><label for="q2b">Test 5</label><br>
<input data-answer type="radio" name="q2" value="c" id="q2c"><label for="q2c">Test 6</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 3</h4>
<p>Question 3</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q3" value="a" id="q3a"><label for="q3a">Test 7</label><br>
<input data-answer type="radio" name="q3" value="b" id="q3b"><label for="q3b">Test 8</label><br>
<input data-answer type="radio" name="q3" value="c" id="q3c"><label for="q3c">Test 9</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 4</h4>
<p>Question 4</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q4" value="a" id="q4a"><label for="q4a">Test 10</label><br>
<input data-answer type="radio" name="q4" value="b" id="q4b"><label for="q4b">Test 11</label><br>
<input data-answer type="radio" name="q4" value="c" id="q4c"><label for="q4c">Test 12</label><br>
</div>
<button id="btn-submit" class="btn btn-submit" type="submit" name="submit" value="submit">submit</button>
</form>
</div>
</section>
JavaScript:
function submitAnswer() {
var total = 4;
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;
// Validation
for(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 = ["a", "b", "c", "a"];
// Check Answers
for(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>';
return false;
}
I would be really appreciated for any kind of help. Cheers
You can use classLis.add() for that. So in your JS you'd do
document.getElementById('q4a').classList.add('correct')
document.getElementById('q4b').classList.add('wrong')
document.getElementById('q4c').classList.add('wrong')

onClick is not reacting in quiz

I'm doing this project for school with a quiz in JavaScript. After clicking the button I want it to show a message but for some reason after clicking nothing happens. Could you guys help me? I went through it few times and still don't know what's wrong;/
function check() {
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var question4 = document.quiz.question4.value;
var question5 = document.quiz.question5.value;
var question6 = document.quiz.question6.value;
var question7 = document.quiz.question7.value;
var question8 = document.quiz.question8.value;
var correct = 0;
if (question1 == "voldoende" || "goed") {
correct++;
}
if (question2 == "Voldoende" || "Goed") {
correct++;
}
if (question3 == "Voldoende" || "Goed") {
correct++;
}
if (question4 == "Voldoende" || "Goed") {
correct++;
}
if (question5 == "Voldoende" || "Goed") {
correct++;
}
if (question6 == "Voldoende" || "Goed") {
correct++;
}
if (question7 == "Voldoende" || "Goed") {
correct++;
}
if (question8 == "Voldoende" || "Goed") {
correct++;
}
var messages = ["You passed!", "You failed", "You did awesome"];
var range;
if (correct < 5) {
range = 1;
}
if (correct > 5 && correct < 8) {
range = 0;
}
if (correct == 8) {
range = 2;
}
document.getElementById("after_submit").style.visibility = "visible";
document.getElementById("message").innerHTML = messages[range];
}
body {
font-family: 'Lato', sans-serif;
}
after_submit {
visibility: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/stylesheets.css"> </head>
<body>
<h1>Will I get a good grade for this project?</h1>
<form id="quiz" name="quiz">
<p>Is my code interactief?</p>
<input id="mc" type="radio" name="Question1" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question1" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question1" value="goed">Goed
<br>
<p>Dom Manipulatie</p>
<input id="mc" type="radio" name="Question2" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question2" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question2" value="goed">Goed
<br>
<p>Controle Structuren</p>
<input id="mc" type="radio" name="Question3" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question3" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question3" value="goed">Goed
<br>
<p>Loops</p>
<input id="mc" type="radio" name="Question4" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question4" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question4" value="goed">Goed
<br>
<p>Array/object</p>
<input id="mc" type="radio" name="Question5" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question5" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question5" value="goed">Goed
<br>
<p>Functies</p>
<input id="mc" type="radio" name="Question6" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question6" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question6" value="goed">Goed
<br>
<p>Flow</p>
<input id="mc" type="radio" name="Question7" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question7" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question7" value="goed">Goed
<br>
<p>Kwaliteit</p>
<input id="mc" type="radio" name="Question8" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question8" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question8" value="goed">Goed
<br>
<input id="button" type="button" value="Check my grade" onclick="check();"> </form>
<div id="after_submit">
<p id="message"></p>
<p id="number_correct"></p>
</div>
<script src="js/game.js"></script>
</body>
</html>
You need to change all your question1.value question2.value... to Question1.value Question2.value ... since that's the name of your inputs
But you still need to check your logic because no matter which choice you select on your radio buttons, you always get the message "You did awesome"
Press F12 to see Developer tools. In the Console, you'll see error messages like this:
Uncaught TypeError: Cannot read property 'value' of undefined
That means that document.quiz.question1, ... are not defined. Why? Because properties names are wrong. Write (note the uppercase character):
document.quiz.Question1
I've spotted MANY ERRORS in your code (Either programmaticly or
logically) 1. Goed is not the same with goed, so as
Voldoende and voldoende (Consider consistency of case whether it's HTML or Javascript. Yes, HTML is not a Case-sensitive language
but Javascript do. 2. 5 points shows undefined -> must use
correct <= 5 condition 3. Logical Operation Related Concern
-> question1 == "voldoende" is not the same as "voldoende" (Solution: still rewrite question1 == value on the right side of or
operator) -> this is also the main reason why you always get 8 points. (Right side of the or operator is ALWAYS TRUE, you're just restating that "goed" == "goed" if you don't include the questionN == code)
Lastly #Jérémie L's statement, F12 Developer tools which he have
used, is basically the thing to use to address such problems :) It
helps alot. Use breakpoints to know the value of each line / blocks
of codes.
Snippet below contains correct script of your project.
I've put comment tags on the changes for readability
function check() {
<!-- question1 to Question1, right side of assignment operator -> due to case sensitivity, must be first letters capitalized in both JS and HTML -->
var question1 = document.quiz.Question1.value;
var question2 = document.quiz.Question2.value;
var question3 = document.quiz.Question3.value;
var question4 = document.quiz.Question4.value;
var question5 = document.quiz.Question5.value;
var question6 = document.quiz.Question6.value;
var question7 = document.quiz.Question7.value;
var question8 = document.quiz.Question8.value;
var correct = 0;
<!-- goed on the right side of logical operator must contain question1 == on its left, always remember -->
if (question1 == "voldoende" || question1 == "goed") {
correct++;
}
if (question2 == "voldoende" || question2 == "goed") {
correct++;
}
if (question3 == "voldoende" || question3 == "goed") {
correct++;
}
if (question4 == "voldoende" || question4 == "goed") {
correct++;
}
if (question5 == "voldoende" || question5 == "goed") {
correct++;
}
if (question6 == "voldoende" || question6 == "goed") {
correct++;
}
if (question7 == "voldoende" || question7 == "goed") {
correct++;
}
if (question8 == "voldoende" || question8 == "goed") {
correct++;
}
var messages = ["You passed!", "You failed", "You did awesome"];
var range;
<!-- correct < 5 to correct <= 5, making no space for undefined message -->
if (correct <= 5) {
range = 1;
}
if (correct > 5 && correct < 8) {
range = 0;
}
if (correct == 8) {
range = 2;
}
document.getElementById("after_submit").style.visibility = "visible";
document.getElementById("message").innerHTML = messages[range];
}
body {
font-family: 'Lato', sans-serif;
}
after_submit {
visibility: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/stylesheets.css"> </head>
<body>
<h1>Will I get a good grade for this project?</h1>
<form id="quiz" name="quiz">
<p>Is my code interactief?</p>
<input id="mc" type="radio" name="Question1" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question1" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question1" value="goed">Goed
<br>
<p>Dom Manipulatie</p>
<input id="mc" type="radio" name="Question2" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question2" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question2" value="goed">Goed
<br>
<p>Controle Structuren</p>
<input id="mc" type="radio" name="Question3" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question3" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question3" value="goed">Goed
<br>
<p>Loops</p>
<input id="mc" type="radio" name="Question4" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question4" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question4" value="goed">Goed
<br>
<p>Array/object</p>
<input id="mc" type="radio" name="Question5" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question5" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question5" value="goed">Goed
<br>
<p>Functies</p>
<input id="mc" type="radio" name="Question6" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question6" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question6" value="goed">Goed
<br>
<p>Flow</p>
<input id="mc" type="radio" name="Question7" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question7" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question7" value="goed">Goed
<br>
<p>Kwaliteit</p>
<input id="mc" type="radio" name="Question8" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question8" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question8" value="goed">Goed
<br>
<input id="button" type="button" value="Check my grade" onclick="check();"> </form>
<div id="after_submit">
<p id="message"></p>
<p id="number_correct"></p>
</div>
<script src="js/game.js"></script>
</body>
</html>

JavaScript - How to show the next div and hide the previous one?

I am creating a simple quiz and would like to know how to show one question at a time but only using JavaScript. I do not know jQuery. Essentially, I would like the first question to be shown automatically.
Here is an example of what my HTML looks like:
<div id="q0">
<li>
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</li>
</div>
<div id="q1" style="visibility:hidden">
<li>
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</li>
</div>
<div id="q2" style="visibility:hidden">
<li>
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</li>
</div>
I currently don't have script for showing next div and hiding the previous one because I don't know how to even start.
I'm looking to have it put into this form...
function nextQ(){
// code
}
... and for it to be called by this button:
<button onclick="next()">Next Question</button>
I am really new to HTML and JavaScript and would appreciate any help.
Thanks.
Pure JavaScript version (config):
var showing = [1, 0, 0];
var questions = ['q0', 'q1', 'q2'];
function next() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i < showing.length; i++) {
if (showing[i] == 1) {
qElems[i].style.display = 'none';
showing[i] = 0;
if (i == showing.length - 1) {
qElems[0].style.display = 'block';
showing[0] = 1;
} else {
qElems[i + 1].style.display = 'block';
showing[i + 1] = 1;
}
break;
}
}
}
<div id="questions">
<div id="q0">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</div>
<div id="q1" style="display: none">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</div>
<div id="q2" style="display: none">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</div>
</div>
<button onclick="next()">Next Question</button>
Pure JavaScript version (no config):
function next() {
var qElems = document.querySelectorAll('#questions>div');
for (var i = 0; i < qElems.length; i++) {
if (qElems[i].style.display != 'none') {
qElems[i].style.display = 'none';
if (i == qElems.length - 1) {
qElems[0].style.display = 'block';
} else {
qElems[i + 1].style.display = 'block';
}
break;
}
}
}
<div id="questions">
<div id="q0">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</div>
<div id="q1" style="display: none;">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</div>
<div id="q2" style="display: none;">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</div>
</div>
<button onclick="next()">Next Question</button>
jQuery version:
$(function() {
$('.next').on('click', function() {
$('#questions>div').each(function() {
var id = $(this).index();
if ($(this).is(':visible')) {
$(this).hide();
if (id == $('#questions>div').length - 1) {
$('#questions>div').eq(0).show();
} else {
$('#questions>div').eq(id + 1).show();
}
return false;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="questions">
<div id="q0">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</div>
<div id="q1" style="display: none">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</div>
<div id="q2" style="display: none">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</div>
</div>
<button class="next">Next Question</button>
Though I agree with #Bitwise on using jQuery instead on javascript alone to ensure cross-browser compatibility. But since you insist on using javascript, here's what you should do.
1) Ensure that your <li>'s are enclosed in a container tag first (say, <ul>) so you iterate only through desired list.
2) use display:none property instead of visibility:hidden. visibility:hidden simply hides an element, but it will still take up the same space as before. display:none hides an element, and it will not take up any space.
Here's the updated code.
HTML:
<ul id="listContainer">
<div id="q0">
<li style="display:list-item">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A"/>Green<br/>
<input type="radio" name="question0" value="B"/>Blue<br/>
<input type="radio" name="question0" value="C"/>Red<br/>
<input type="radio" name="question0" value="D"/>Purple<br/>
</li>
</div>
<div id="q1" >
<li style="display:none">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A"/>Water<br/>
<input type="radio" name="question1" value="B"/>Cement<br/>
<input type="radio" name="question1" value="C"/>Trees<br/>
<input type="radio" name="question1" value="D"/>The Sky<br/>
</li>
</div>
<div id="q2" >
<li style="display:none">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A"/>24<br/>
<input type="radio" name="question2" value="B"/>22<br/>
<input type="radio" name="question2" value="C"/>16<br/>
<input type="radio" name="question2" value="D"/>48<br/>
</li>
</div>
</ul>
<button id="next">next</button>
Javascript:
document.getElementById('next').addEventListener("click",function(){
var listContainer = document.getElementById("listContainer");
var listItem = listContainer.getElementsByTagName("li");
for (var i=0; i < listItem.length-1; i++)
{
if(listItem[i].style.display == "list-item")
{
listItem[i].style.display = "none";
listItem[i+1].style.display = "list-item";
break;
}
}
});
Here's the fiddle.
Cheers!
I would twist the code a little. Add question class to every div which acts as question i.e .question { display:none }. Add active class to first question (i.e. .active{display:block}, it shows the first question. Look for all divs with question class and add them to a variable, with every next button pressed,remove active class from current question add active class to next div with class question using classList.add and classList.remove of Javascript until last question is reached. Count keeps the current question's number.
I've done it in the codepen http://codepen.io/dwanirdesh/pen/EaQOPg
Or code directly from below:
<div id="q0" class="question active">
<li>
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</li>
</div>
<div id="q1" class="question" >
<li>
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</li>
</div>
<div id="q2" class="question">
<li>
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</li>
</div>
<button onclick="next()">Next Question</button>
## CSS ##
.question{
display:none
}
.active{
display:block
}
## JAVASCRIPT ##
var questionNumber=0;
var questions=document.querySelectorAll('.question');
function next(){
questionNumber++;
if(questions.length>questionNumber)
{
document.querySelector('.active').classList.remove('active');
questions[questionNumber].classList.add('active');
}
}
Here is the java script function code. For this to work, you need to make sure that the div display property to be set as or in the html code. Also you need to name the id of the button to be "next" so that it can be hidden on reaching the last button.
function nextQ(){
var blockFound = 0;
var lastQuestion = 0;
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
if ( blockFound == 1){
blockFound = 0;
divs[i].style.display = 'block';
}else if ( divs[i].style.display == 'block' ){
if ( i + 2 == divs.length){
lastQuestion = 1;
}
blockFound = 1;
divs[i].style.display = 'none';
}
}
if ( lastQuestion == 1){
document.getElementById('next').style.visibility = 'hidden';
}
}
Html code here.
<div id="q0" style="display:block">
<li>
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</li>
</div>
<div id="q1" style="display:none">
<li>
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</li>
</div>
<div id="q2" style="display:none">
<li>
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</li>
</div>
<button id="next" onclick="nextQ()">Next Question</button>
Is it what you need?
<div id="q0">
<li>
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</li>
<button class="next" onclick="goNext(0)">Next Question</button>
</div>
<div id="q1" style="display:none">
<li>
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</li>
<button class="next" onclick="goNext(1)">Next Question</button>
</div>
<div id="q2" style="display:none">
<li>
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</li>
<button class="next" onclick="goNext(2)">Next Question</button>
</div>
<script language=javascript>
function goNext(i)
{
document.getElementById("q"+i).style.display = 'none';
i++;
document.getElementById("q"+i).style.display = 'block';
}
</script>

Trying to use Javascript/CSS to change a property, but can't get it to work within an if/else statement?

So you're my last hope.
I need to create a quiz, that validates name and email. Once the name and email have been validated ONLY THEN will the quiz show up. Thing is, when I put my code of
function changeStyle() {
if (document.getElementById('quiz').style.display == "none") {
document.getElementById('quiz').style.display = "block";
} else {
document.getElementById('quiz').style.display = "none";
}
}
in, my if/else statement it doesn't work. Running this code outside of the if/else statement works, albeit simply on the click of a button. The alert in the if/else statement runs as well, as does the rest of script afterwards. It seems to be just ignoring this script. Here is the Jquery i'm using:
$(document).ready(function() {
$('#contact_name').on('input', function() {
var input = $(this);
var re = /^[A-Za-z0-9]+ [A-Za-z0-9]+$/;
var is_name = re.test(input.val());
if (is_name) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#contact_email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$("#contact_submit button").click(function(event) {
var form_data = $("#contact").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_" + form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
} else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
event.preventDefault();
} else {
alert('This alert is working');
function changeStyle() {
if (document.getElementById('quiz').style.display == "none") {
document.getElementById('quiz').style.display = "block";
} else {
document.getElementById('quiz').style.display = "none";
}
}
}
});
});
CSS:
#quiz{
display:none;
}
Please help! I have tried body:onload aswell, but it seems to just have the same issue. And I've already scoured the internet for answers. I seem to be missing something, I just don't know what.
Thanks
EDIT* changeStyle is being called. Here is the HTML relating to this part.
<form id="contact" method="post" action="">
<!-- Name -->
<div>
<label for="contact_name">Name:</label>
<input type="text" id="contact_name" name="name"></>
<span class="error">This field is required</span>
</div>
<!-- Email -->
<div>
<label for="contact_email">Email:</label>
<input type="email" id="contact_email" name="email"></>
<span class="error">A valid email address is required</span>
</div>
<!-- Submit Button -->
<div id="contact_submit">
<button type="button" onclick="show()">Submit</button> </div>
</form>
<content>
<form id="quiz" name="quiz">
<h1>Test your CSS knowledge!</h1>
<h3>What does CSS stand for?</h3>
<fieldset class="question">
<input type="radio" id="q1a1" class="answer" value="Cascading CSS" data- correct="false" name="q1" ><label for="q1a1">Cascading Css</label><br>
<input type="radio" id="q1b2" class="answer" value="Cascading Style Sheets" data-correct="true" name="q1"><label for="q1b2">Cascading Style Sheets</label><br>
<input type="radio" id="q1c3" class="answer" value="Cascading Seperate Style" data-correct="false" name="q1"><label for="q1c3">Cascading Separate Style</label><br>
</fieldset>
<h3>Which attribute can be set to bold?</h3>
<fieldset class="question">
<input type="radio" id="q2a1" class="answer" value="Text Decoration" data-correct="false" name="q2" ><label for="q2a1">Text Decoration</label><br>
<input type="radio" id="q2b2" class="answer" value="Font Style" data-correct="false" name="q2"><label for="q2b2">Font Style</label><br>
<input type="radio" id="q2c3" class="answer" value="Font Weight" data-correct="true" name="q2"><label for="q2c3">Font Weight</label><br>
</fieldset>
<h3>Which tag is used to link an external CSS file?</h3>
<fieldset class="question">
<input type="radio" id="q3a1" class="answer" value="Script" data-correct="false" name="q3" ><label for="q3a1">Script</label><br>
<input type="radio" id="q3b2" class="answer" value="Link" data-correct="true" name="q3"><label for="q3b2">Link</label><br>
<input type="radio" id="q3c3" class="answer" value="Rel" data-correct="false" name="q3"><label for="q3c3">Rel</label><br>
</fieldset>
<h3>Which attribute sets the underline property?</h3>
<fieldset class="question">
<input type="radio" id="q4a1" class="answer" value="Font Style" data-correct="false" name="q4" ><label for="q4a1">Font Style</label><br>
<input type="radio" id="q4b2" class="answer" value="Text Decoration" data-correct="true" name="q4"><label for="q4b2">Text Decoration</label><br>
<input type="radio" id="q4c3" class="answer" value="Font Weight" data-correct="false" name="q4"><label for="q4c3">Font Weight</label><br>
</fieldset>
<h3>Which element is NOT relative?</h3>
<fieldset class="question">
<input type="radio" id="q5a1" class="answer" value="Px" data-correct="true" name="q5" ><label for="q5a1">Px</label><br>
<input type="radio" id="q5b2" class="answer" value="Cm" data-correct="false" name="q5"><label for="q5b2">Cm</label><br>
<input type="radio" id="q5c3" class="answer" value="%" data-correct="false" name="q5"><label for="q5c3">%</label><br>
<input type="radio" id="q5d4" class="answer" value="Em" data-correct="false" name="q5"><label for="q5d4">Em</label><br>
</fieldset>
<h3>Which element IS relative?</h3>
<fieldset class="question">
<input type="radio" id="q6a1" class="answer" value="Em" data-correct="true" name="q6" ><label for="q6a1">Em</label><br>
<input type="radio" id="q6b2" class="answer" value="Cm" data-correct="false" name="q6"><label for="q6b2">Cm</label><br>
<input type="radio" id="q6c3" class="answer" value="MM" data-correct="false" name="q6"><label for="q6c3">MM</label><br>
<input type="radio" id="q6d4" class="answer" value="Inch" data-correct="false" name="q6"><label for="q6d4">Inch</label><br>
</fieldset>
<h3>What attribute is used to move an elements content away from its border?</h3>
<fieldset class="question">
<input type="radio" id="q7a1" class="answer" value="Margin" data-correct="false" name="q7" ><label for="q7a1">Margin</label><br>
<input type="radio" id="q7b2" class="answer" value="Padding" data-correct="true" name="q7"><label for="q7b2">Padding</label><br>
<input type="radio" id="q7c3" class="answer" value="Border" data-correct="false" name="q7"><label for="q7c3">Border</label><br>
<input type="radio" id="q74d" class="answer" value="Width" data-correct="false" name="q7"><label for="q7d4">Width</label><br>
</fieldset>
<h3>Which element does not contribute to a block elements total width?</h3>
<fieldset class="question">
<input type="radio" id="q8a1" class="answer" value="Width" data-correct="false" name="q8" ><label for="q8a1">Width</label><br>
<input type="radio" id="q8b2" class="answer" value="Border" data-correct="false" name="q8"><label for="q8b2">Border</label><br>
<input type="radio" id="q8c3" class="answer" value="Background-image" data-correct="true" name="q8"><label for="q8c3">Background-image</label><br>
<input type="radio" id="q8d4" class="answer" value="Padding" data-correct="false" name="q8"><label for="q8d4">Padding</label><br>
</fieldset>
<h3>Which property changes positioned elements display order?</h3>
<fieldset class="question">
<input type="radio" id="q9a1" class="answer" value="Width" data-correct="false" name="q9" ><label for="q9a1">Width</label><br>
<input type="radio" id="q9b2" class="answer" value="Background" data-correct="false" name="q9"><label for="q9b2">Background</label><br>
<input type="radio" id="q9c3" class="answer" value="z-index" data-correct="true" name="q9"><label for="q9c3">Z-index</label><br>
<input type="radio" id="q9d4" class="answer" value="Azimuth" data-correct="false" name="q9"><label for="q9d4">Azimuth</label><br>
</fieldset>
<h3>Which value of background-repeat will cause the background to repeat vertically?</h3>
<fieldset class="question">
<input type="radio" id="q10a1" class="answer" value="repeat-x" data-correct="false" name="q10" ><label for="q10a1">repeat-x</label><br>
<input type="radio" id="q10b2" class="answer" value="repeat" data-correct="false" name="q10"><label for="q10b2">repeat</label><<br>
<input type="radio" id="q10c3" class="answer" value="repeat-y" data-correct="true" name="q10"><label for="q10c3">repeat-y</label><br>
<input type="radio" id="q10d4" class="answer" value="No-repeat" data-correct="false" name="q10"><label for="q10d4">No-repeat</label><br>
</fieldset>
<footer>
<fieldset class="calc-percentage" name="score">
<input type="button" id="calc" value="Get score" />
<div>
<p><label for="percentage">Score = </label><input type=text size=15 id="percentage" name="percentage" /></p>
<input type="submit" onclick="checkQuiz()">
</div>
</fieldset>
You only redefine function changeStyle(){}, never calling it. Also, if you're going to use jQuery then use it. Just use .css(), if you don't want to .toggle(). Get rid of onclick='changeStyle()' in your HTML.
Despite all of your other possible errors:
$(document).ready(function(){
$('#contact_name').on('input', function(){
var input = $(this);
var re = /^[A-Za-z0-9]+ [A-Za-z0-9]+$/;
var is_name = re.test(input.val());
if(is_name){
input.removeClass('invalid').addClass('valid');
}
else{
input.removeClass('valid').addClass('invalid');
}
});
$('#contact_email').on('input', function(){
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if(is_email){
input.removeClass('invalid').addClass('valid');
}
else {
input.removeClass('valid').addClass('invalid');
}
});
$('#contact_submit button').click(function(event){
var form_data = $('#contact').serializeArray(), error_free = true;
for(var input in form_data){
var element = $('#contact_' + form_data[input]['name']);
var valid = element.hasClass('valid');
var error_element = $('span', element.parent());
if(!valid){
error_element.removeClass('error').addClass('error_show');
error_free = false;
}
else{
error_element.removeClass('error_show').addClass('error');
}
}
if(!error_free){
event.preventDefault();
}
else{
// look what changed here - you have to call a function to execute it
$('#quiz').css('display', 'block');
}
});
});
Again get rid of your regular JavaScript function changeStyle() and remove it from HTML, as well!!!

Categories

Resources