Start button doesn't show questions when startover button is clicked - javascript

I am working on a quiz. My start button is supposed to show the first question/answers when clicked and it does (the first time I use it).
In fact, when I click on my startover button at the end of the quiz (once results are shown), it brings me back to the first "page" with the start button (to start the quiz again) but when I click the start button, thought the progress bar does show, the question doesn't!
So basically, my start button works to start the quiz but if you want to start over the quiz again you can't because in this case it only shows the progress bar and nothing else.
This is my code:
$(document).ready(function(){ // DOC READY
var totalQuestions = $('.questionarea').length; // VARIABLES
var currentQuestion = 0;
var $progressbar = $("#progressbar");
var score = 0;
var value = 0;
$questions = $('.questionarea');
$questions.hide();
$("#startover").on("click", function(){ // STARTOVER
$(this).hide();
$(".answers").hide();
$("#images").hide();
$("#score").hide();
$(".btn-lg").show();
score = 0;
value = 0;
currentQuestion = 0;
$progressbar.val(value);
$questions.hide();
});
$(document).on("click", ".btn-lg", function(){ // START BUTTON FADE OUT
$(this).hide();
$progressbar.show(200);
$(".answers").show(200);
$($questions.get(currentQuestion)).fadeIn();
});
$(document).on("click", '.answers input', function(){ // NEW QUESTIONS FADE IN + PROGRESS BAR
$($questions.get(currentQuestion)).fadeOut(200, function () {
currentQuestion ++;
if (currentQuestion === totalQuestions){
$("#results").fadeIn(200);
}
else {
$questions.eq(currentQuestion).fadeIn(200);
}
value = value + 10;
$progressbar.val(value);
});
});
function calcScore() { // OPTIONS CHECKED
var house1 = document.getElementById('option1').checked;
var house2 = document.getElementById('option8').checked;
var house3 = document.getElementById('option11').checked;
var house4 = document.getElementById('option16').checked;
var house5 = document.getElementById('option18').checked;
var house6 = document.getElementById('option23').checked;
var house7 = document.getElementById('option27').checked;
var house8 = document.getElementById('option32').checked;
var house9 = document.getElementById('option35').checked;
var house10 = document.getElementById('option36').checked;
var sher1 = document.getElementById('option2').checked;
var sher2 = document.getElementById('option6').checked;
var sher3 = document.getElementById('option10').checked;
var sher4 = document.getElementById('option14').checked;
var sher5 = document.getElementById('option19').checked;
var sher6 = document.getElementById('option24').checked;
var sher7 = document.getElementById('option26').checked;
var sher8 = document.getElementById('option29').checked;
var sher9 = document.getElementById('option33').checked;
var sher10 = document.getElementById('option37').checked;
var cas1 = document.getElementById('option3').checked;
var cas2 = document.getElementById('option7').checked;
var cas3 = document.getElementById('option9').checked;
var cas4 = document.getElementById('option15').checked;
var cas5 = document.getElementById('option17').checked;
var cas6 = document.getElementById('option21').checked;
var cas7 = document.getElementById('option28').checked;
var cas8 = document.getElementById('option30').checked;
var cas9 = document.getElementById('option33').checked;
var cas10 = document.getElementById('option38').checked;
var brbad1 = document.getElementById('option4').checked;
var brbad2 = document.getElementById('option5').checked;
var brbad3 = document.getElementById('option12').checked;
var brbad4 = document.getElementById('option13').checked;
var brbad5 = document.getElementById('option20').checked;
var brbad6 = document.getElementById('option22').checked;
var brbad7 = document.getElementById('option25').checked;
var brbad8 = document.getElementById('option31').checked;
var brbad9 = document.getElementById('option34').checked;
var brbad10 = document.getElementById('option39').checked;
if(house1 === true){ // SCORE CALCULATION
score += 1;
}
if(house2 === true){
score += 1;
}
if(house3 === true){
score += 1;
}
if(house4 === true){
score += 1;
}
if(house5 === true){
score += 1;
}
if(house6 === true){
score += 1;
}
if(house7 === true){
score += 1;
}
if(house8 === true){
score += 1;
}
if(house9 === true){
score += 1;
}
if(house10 === true){
score += 1;
}
if(sher1 === true){
score += 2;
}
if(sher2 === true){
score += 2;
}
if(sher3 === true){
score += 2;
}
if(sher4 === true){
score += 2;
}
if(sher5 === true){
score += 2;
}
if(sher6 === true){
score += 2;
}
if(sher7 === true){
score += 2;
}
if(sher8 === true){
score += 2;
}
if(sher9 === true){
score += 2;
}
if(sher10 === true){
score += 2;
}
if(cas1 === true){
score += 3;
}
if(cas2 === true){
score += 3;
}
if(cas3 === true){
score += 3;
}
if(cas4 === true){
score += 3;
}
if(cas5 === true){
score += 3;
}
if(cas6 === true){
score += 3;
}
if(cas7 === true){
score += 3;
}
if(cas8 === true){
score += 3;
}
if(cas9 === true){
score += 3;
}
if(cas10 === true){
score += 3;
}
if(brbad1 === true){
score += 4;
}
if(brbad2 === true){
score += 4;
}
if(brbad3 === true){
score += 4;
}
if(brbad4 === true){
score += 4;
}
if(brbad5 === true){
score += 4;
}
if(brbad6 === true){
score += 4;
}
if(brbad7 === true){
score += 4;
}
if(brbad8 === true){
score += 4;
}
if(brbad9 === true){
score += 4;
}
if(brbad10 === true){
score += 4;
}
// CHARACTER SCORE
if(score < 12){
score = "House & Wilson!";
$("#houseimage").show();
}
if(score <= 20){
score = "Sherlock & John!";
$("#sherimage").show();
}
if(score <= 30){
score = "Dean & Cas!";
$("#casimage").show();
}
if(score <= 40){
score = "Walt & Jesse!";
$("#brbadimage").show();
}
}
// SHOW RESULTS
$("#results").click(function(){
$(this).hide();
$progressbar.hide();
$("#startover").show();
calcScore();
$("#score").show();
document.getElementById("score").innerText = 'You Got: ' + score;
});
});
body {
background-image: url("http://wallpoper.com/images/00/40/76/15/gregory-house_00407615.jpg");
background-size: cover;
background-repeat: no-repeat;
overflow: hidden;
background-position: fixed;
}
.header {
margin-top: 30px;
}
#title {
font-size: 30px;
text-align: center;
font-family: fantasy, serif;
margin-top: 50px;
margin: 0 auto;
float: none;
}
.box {
width: 900px;
height: 450px;
background-color: #ba348b;
border-radius: 40px;
box-shadow: 4px 4px 10px 4px black;
padding: auto;
overflow: hidden;
text-align: center;
margin: 0 auto;
margin-bottom: 20px;
margin-top: 30px;
float: none;
}
// START QUIZ BUTTON
#start {
background-color: #00c6d2;
border: 2px solid #13281c;
border-radius: 10px;
color: #13281c;
padding: 20px;
width: 200px;
opacity: 1;
margin-top: 110px;
font-size: 20px;
font-family: fantasy, serif;
&:hover {
background-color:
#009ea8;
}
}
.btn-lg {
float: none;
margin: 0 auto;
text-align:center;
margin-top: 70px;
margin-left: 10px;
}
// PROGRESS BAR
.divprogress {
text-align: center;
float: none;
margin: 0 auto;
}
#progressbar {
background-color: blue;
margin: 0 auto;
float: none;
box-shadow: none;
outline: none;
text-align: center;
width: 780px;
margin-left: auto;
margin-right:auto;
margin-top: 20px;
display: none;
}
// QUESTIONS AND ANSWERS
#QA1, #QA2, #QA3, #QA4, #QA5, #QA6, #QA7, #QA8, #QA9, #QA10 {
margin-top: 10px;
font-family: fantasy, serif;
color: #13281c;
display: none;
}
.questionarea {
display: none;
}
.col-lg-6 {
float: none;
margin: 0 auto;
margin-top: -40px;
}
.question1, .question2, .question3, .question4, .question5, .question6, .question7, .question8, .question9, .question10 {
font-size: 18px;
font-family: fantasy, serif;
margin-top: 70px;
margin-bottom: 30px;
}
.btn-primary {
font-size: 14px;
background-color: #ffff32 !important;
color: #13281c !important;
outline: 0 none;
opacity: 1;
border: 0 none;
&:hover{
background-color: #e5e500 !important;
color: black !important;
outline: 0 none;
}
}
// RESULTS BUTTON / TEXT
#results {
padding: 20px;
background-color: #609D57;
border: 3px solid darkgreen;
border-radius: 10px;
display: none;
text-align: center;
font-family: fantasy, serif;
float: center;
margin-top: 90px;
font-size: 18px;
color: #13281c !important;
outline: 0 none;
opacity: 1;
&:hover{
background-color: #568d4e !important;
color: black !important;
outline: 0 none;
}
}
#score {
text-align: center;
font-size: 20px;
font-family: fantasy, serif;
float: center;
color: #920602;
}
#startover{
text-align: center;
font-size: 14px;
font-family: fantasy, serif;
margin-top: 20px;
float: center;
display: none;
background-color: rgba(211,211,211, 0.7);
&:hover {
background-color: rgba(211,211,211, 1);
}
}
// IMAGES
#houseimage, #sherimage, #casimage, #brbadimage {
display: none;
text-align: center;
margin-top: 10px;
}
#houseimage, #sherimage, #brbadimage {
height: 240px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container box">
<div class="header">
<div class="text-center" id="title"> WHICH TV BROMANCE ARE YOU AND YOUR BFF? </div></div>
<div class="col-sm-11 text-center divprogress">
<div class="text-center">
<progress class="progress progress-striped progress-animated center-block" style="width: 0%, text-align: center" id="progressbar" value="0" max="100"></progress> </div></div>
<br>
<br>
<div class="col-lg-6 text-center">
<button type="button" class="btn btn-secondary btn-lg text-center" id="start">START QUIZ</button></div>
<!-- QUIZ AREA -->
<!-- QUESTION & ANSWERS 1 -->
<div id="content">
<div class="questionarea text-center" id="QA1" data-question"1">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question1">Q1: How did you and your BFF meet?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question1" value="1" id="option1"> At work </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question1" value="2" id="option2"> Living together</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question1" value="3" id="option3"> Under unusual or other circumstances</label></div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question1" value="4" id="option4"> In school</label></div></div>
</div>
<!-- QUESTION & ANSWERS 2 -->
<div class="questionarea text-center" id="QA2" data-question"2">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question2">Q2: How long have you known each other?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question2" value="4" id="option5"> Less than 3 years </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question2" value="2" id="option6"> 4-7 years</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question1" value="3" id="option7"> At least 8 years</label></div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question2" value="1" id="option8"> Over 20 years</label></div></div>
</div>
<!-- QUESTION & ANSWERS 3 -->
<div class="questionarea text-center" id="QA3" data-question"3">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question3">Q3: How would you describe your friendship?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question3" value="3" id="option9"> Deep </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question3" value="2" id="option10"> Amazing</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question1" value="1" id="option11"> Needy</label></div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question3" value="4" id="option12"> Protective</label></div></div>
</div>
<!-- QUESTION & ANSWERS 4 -->
<div class="questionarea text-center" id="QA4" data-question"3">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question4">Q4: What do you do together?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question4" value="4" id="option13"> Business </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question4" value="2" id="option14"> Go out</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question4" value="3" id="option15"> Just hold each other</label> </div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question4" value="1" id="option16"> Play pranks on each other</label></div></div>
</div>
<!-- QUESTION & ANSWERS 5 -->
<div class="questionarea text-center" id="QA5" data-question"4">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question5">Q5: How often do you fight?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question5" value="3" id="option17"> Not much, but when we do, it's a big deal </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question5" value="1" id="option18"> We have lots of harmless tiffs</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question5" value="2" id="option19"> Sometimes</label> </div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question5" value="4" id="option20"> Often and it can get physical</label></div></div>
</div>
<!-- QUESTION & ANSWERS 6 -->
<div class="questionarea text-center" id="QA6" data-question"4">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question6">Q6: How well do you know each other?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question6" value="3" id="option21"> Quite a lot </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question6" value="4" id="option22"> Not much</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question6" value="1" id="option23"> We know every detail of each other's lives</label> </div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question6" value="2" id="option24"> He knows way more about my life than I know about his (or viceversa)</label></div></div>
</div>
<!-- QUESTION & ANSWERS 7 -->
<div class="questionarea text-center" id="QA7" data-question"4">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question7">Q7: Do you celebrate your birthdays together?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question7" value="4" id="option25"> No, but I buy him a great present </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question7" value="2" id="option26"> Of course</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question7" value="1" id="option27"> Often</label> </div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question7" value="3" id="option28"> Only if he's in town at the time</label></div></div>
</div>
<!-- QUESTION & ANSWERS 8 -->
<div class="questionarea text-center" id="QA8" data-question"4">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question8">Q8: How often are you around each other's houses?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question8" value="2" id="option29"> We live together </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question8" value="3" id="option30"> Often</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question8" value="4" id="option31"> Not often</label></div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question8" value="1" id="option32"> All the time</label></div></div>
</div>
<!-- QUESTION & ANSWERS 9 -->
<div class="questionarea text-center" id="QA9" data-question"4">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question9">Q9: How often do you talk about your feelings?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question9" value="3" id="option33"> No need. We can see right through each other </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question9" value="2" id="option33"> Occasionally</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question9" value="4" id="option34"> Rarely</label></div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question9" value="1" id="option35"> Only in a joking manner</label></div></div>
</div>
<!-- QUESTION & ANSWERS 10 -->
<div class="questionarea text-center" id="QA10" data-question"4">
<ul class="col-lg-6 list-group text-center">
<p class="list-group-item question10">Q10: What do you consider each other as?</p>
</ul>
<br>
<div class="answers">
<div id="divoption1">
<label class="btn btn-primary">
<input type="radio" name="question10" value="1" id="option36"> Life partners </label></div>
<br>
<div id="divoption2">
<label class="btn btn-primary">
<input type="radio" name="question10" value="2" id="option37"> Best friends</label></div>
<br>
<div id="divoption3"><label class="btn btn-primary">
<input type="radio" name="question10" value="3" id="option38"> Family (brothers)</label></div>
<br>
<div id="divoption4">
<label class="btn btn-primary">
<input type="radio" name="question10" value="4" id="option39"> Family (father/son)</label></div></div>
</div>
<!-- ---- -->
<button id="results">View Results</button>
<h2 id='score'></h2>
<div id="images">
<img id="houseimage" src="http://24.media.tumblr.com/tumblr_m70pdclcae1qcy01ao1_500.gif" />
<img id="brbadimage" src="http://24.media.tumblr.com/c88e253d9ed37f2cf422bf4bef27bcbc/tumblr_n52r45b3YW1qglx18o1_r1_250.gif" />
<img id="sherimage" src="http://read.html5.qq.com/image?src=forum&q=5&r=0&imgflag=7&imageUrl=http://mmbiz.qpic.cn/mmbiz/4vhrz0icYkiaUHCPsiaJUKMEsFnUWwluggISyy0iaAaZvhOxcKhdc3XLK8LhSc3q52lOaIvBzsuZP93STzKEyqoYBw/0?wx_fmt=gif" />
<img id="casimage" src="http://66.media.tumblr.com/9c0723fa2ff4054cea2d0a530802fef8/tumblr_inline_mtnsncH2fn1qjt6x6.gif" />
</div>
<div><button id="startover">Start Over</button></div>
</div>
</div>
</body>

$("#startover").on("click", function(){ // STARTOVER
$(this).hide();
$('#option1').removeAttr('checked');
$('#option2').removeAttr('checked');
/// and so on for rest of options use an array/loop to be more elegant
//$("#images").hide(); dont want to hide slideshow
$("#score").hide();
$(".btn-lg").show();
score = 0;
value = 0;
currentQuestion = 0;
$progressbar.val(value);
$questions.hide();
});

Related

Putting some 2 second breaks between questions in already made jquery code

I have a jquery code which is useful for changing one question for another. Questions them self are stored in div's. However, I am trying to work out a solution of how to make some small time brakes between these questions.
The only solution that I have at the moment is to hide/show each div with a question at specific time, but that's really bad code-wise, and I would like to have something that looks pretty and which could be easily changed (time-wise).
jQuery(function() {
var $els = $('div[id^=question]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function() {
$els.eq(i).fadeOut(function() {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 15000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="question1"></div>
<div id="question2" class="question">
<input type="radio" name="q1" value="non" id="non" style="visibility: hidden" checked><br>
<label> <input type="radio" name="q1" value="1" id="guess" class="radio" >Rain</label>
<label> <input type="radio" name="q1" value="2" id="guess" class="radio" >No rain</label><br>
</div> <br>
<div id="question3" class="question">
<input type="radio" name="q2" value="non" id="non" style="visibility: hidden" checked><br>
<label> <input type="radio" name="q2" value="1" id="guess" class="radio" >Rain</label>
<label> <input type="radio" name="q2" value="2" id="guess" class="radio" >No rain</label><br>
</div> <br>
Take a look at my approach. I solved most of it with plain old CSS.
const getNextQuestion = (current) => {
let next = current.nextElementSibling;
if (next.tagName !== 'DIV') {
return;
}
return next;
}
let currentQuestion = document.querySelector('.is-open');
document.querySelector('button').addEventListener('click', () => {
let currentQuestion = document.querySelector('.is-open');
let nextQuestion = getNextQuestion(currentQuestion);
currentQuestion.classList.remove('is-open');
nextQuestion.classList.add('is-open');
currentQuestion = nextQuestion;
});
.question {
border: 1px solid red;
background: tomato;
margin-bottom: 25px;
border-radius: 25px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-family: 'Open Sans';
opacity: 0;
visibility: none;
transition: visibility 1s linear, opacity 1s linear;
}
.is-open {
opacity: 1;
visibility: visible;
}
<div>
<div class="question is-open">
Question 1
</div>
<div class="question">
Questi
<div>
<div class="question is-open">
Question 1
</div>
<div cla<div>
<div class="question is-open">
Question 1
</div>
<div class="question">
Question 2
</div>
</div>
<button>
Next Question
</button> ss="question"> Question 2
</div>
</div>
<button>
Next Question
</button> on 2
</div>
</div>
<button>
Next Question
</button>

JavaScript validation of radio buttons

Below it's a quiz built with HTML, CSS, and JavaScript and it has 4 questions and I want to make radio buttons of questions to be selected otherwise it will show an alert saying "Please check an option", but it does not work and I can skip questions by pressing button "Next" and leaving options empty.
Any idea how this can be solved?
let question1 = document.getElementById('pytja1');
let question2 = document.getElementById('pytja2');
let question3 = document.getElementById('pytja3');
let question4 = document.getElementById('pytja4');
let result = document.getElementById('bot-submit');
let nextButtons = document.querySelectorAll('.bot');
for (let i = 0; i < nextButtons.length; i++) {
let nextQuestion = nextButtons[i];
nextQuestion.onclick = function() {
switchToNextQuestion(this);
};
}
function switchToNextQuestion(nextQuestion) {
let parentId = nextQuestion.parentNode.id;
if (parentId === 'pytja1') {
question1.style.display = 'none';
question2.style.display = 'block';
} else if (parentId === 'pytja2') {
question2.style.display = 'none';
question3.style.display = 'block';
} else if (parentId === 'pytja3') {
question3.style.display = 'none';
question4.style.display = 'block';
}
}
function validateForm() {
let radios = document.getElementsByName("q1");
let formValid = false;
let i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select one option");
return formValid;
}
form {
width: 100%;
position: relative;
float: left;
padding-top: 50px;
}
.quiz {
margin: 0px auto;
width: 250px;
height: 100px;
position: absolute;
top: 60px;
left: 42%;
}
.quest1,
.quest2,
.quest3,
.quest4 {
background-color: cadetblue;
font-size: 22px;
}
.questions1 {
margin-left: 28px;
background-color: cyan;
width: 220px;
padding: 10px;
font-size: 20px;
}
.questions2 {
background-color: red;
}
.questions3 {
background-color: greenyellow;
}
.questions4 {
background-color: olivedrab;
}
.bot {
margin-top: 10px;
}
#pytja2,
#pytja3,
#pytja4 {
margin-left: 28px;
display: none;
width: 220px;
padding: 10px;
font-size: 20px;
}
<div id = "results">
<form id="quiz-form">
<div class="quiz">
<div id="pytja1" class="questions1">
<span class="quest1">I am a ?</span><br/>
<input type="radio" name="q1" value="male" id="correct"> Male<br/>
<input type="radio" name="q1" value="female" id="correct2"> Female<br/>
<input type="radio" name="q1" value="other" id="correct3"> Other<br/>
<input class="bot" type="button" value="Next" onclick="return validateForm()"/>
</div>
<div id="pytja2" class="questions2">
<span class="quest2">Football has letters ?</span><br/>
<input type="radio" name="q2" value="8" class="correct"> 8<br/>
<input type="radio" name="q2" value="5"> 5<br/>
<input type="radio" name="q2" value="6"> 6<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja3" class="questions3">
<span class="quest3">VW stands for ?</span><br/>
<input type="radio" name="q3" value="BMW" /> BMW <br/>
<input type="radio" name="q3" value="Volkswagen" class="correct" /> Volkswagen<br/>
<input type="radio" name="q3" value="Audi" /> Audi<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja4" class="questions4">
<span class="quest4">What year it is ?</span><br/>
<input type="radio" name="q4" value="2017" /> 2017<br/>
<input type="radio" name="q4" value="2015" /> 2015<br/>
<input type="radio" name="q4" value="2019" class="correct" /> 2019<br/>
<input id="bot-submit" type="submit" value="Submit" />
</div>
</div>
</form>
</div>
You can do this by calling your validateForm() function within the click event handler of your next buttons. This function is returning a boolean, if it's true, call switchToNextQuestion().
To be able to do this we need to make some slight modifications to your code though.
for (let i = 0; i < nextButtons.length; i++) {
let nextQuestion = nextButtons[i];
nextQuestion.onclick = function() {
if (validateForm(i + 1)) {
switchToNextQuestion(this);
}
};
}
Here we're calling validateForm using a newly parameter, which tells the function wich input dialog to validate.
The modified validateForm function:
function validateForm(elementNumber) {
let radios = document.getElementsByName("q" + elementNumber);
let formValid = false;
let i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select one option");
return formValid;
}
Finally a working example:
let question1 = document.getElementById('pytja1');
let question2 = document.getElementById('pytja2');
let question3 = document.getElementById('pytja3');
let question4 = document.getElementById('pytja4');
let result = document.getElementById('bot-submit');
let nextButtons = document.querySelectorAll('.bot');
for (let i = 0; i < nextButtons.length; i++) {
let nextQuestion = nextButtons[i];
nextQuestion.onclick = function() {
if (validateForm(i + 1)) {
switchToNextQuestion(this);
}
};
}
function switchToNextQuestion(nextQuestion) {
let parentId = nextQuestion.parentNode.id;
if (parentId === 'pytja1') {
question1.style.display = 'none';
question2.style.display = 'block';
} else if (parentId === 'pytja2') {
question2.style.display = 'none';
question3.style.display = 'block';
} else if (parentId === 'pytja3') {
question3.style.display = 'none';
question4.style.display = 'block';
}
}
function validateForm(elementNumber) {
let radios = document.getElementsByName("q" + elementNumber);
let formValid = false;
let i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select one option");
return formValid;
}
form {
width: 100%;
position: relative;
float: left;
padding-top: 50px;
}
.quiz {
margin: 0px auto;
width: 250px;
height: 100px;
position: absolute;
top: 60px;
left: 42%;
}
.quest1,
.quest2,
.quest3,
.quest4 {
background-color: cadetblue;
font-size: 22px;
}
.questions1 {
margin-left: 28px;
background-color: cyan;
width: 220px;
padding: 10px;
font-size: 20px;
}
.questions2 {
background-color: red;
}
.questions3 {
background-color: greenyellow;
}
.questions4 {
background-color: olivedrab;
}
.bot {
margin-top: 10px;
}
#pytja2,
#pytja3,
#pytja4 {
margin-left: 28px;
display: none;
width: 220px;
padding: 10px;
font-size: 20px;
}
<div id="results">
<form id="quiz-form">
<div class="quiz">
<div id="pytja1" class="questions1">
<span class="quest1">I am a ?</span><br/>
<input type="radio" name="q1" value="male" id="correct"> Male<br/>
<input type="radio" name="q1" value="female" id="correct2"> Female<br/>
<input type="radio" name="q1" value="other" id="correct3"> Other<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja2" class="questions2">
<span class="quest2">Football has letters ?</span><br/>
<input type="radio" name="q2" value="8" class="correct"> 8<br/>
<input type="radio" name="q2" value="5"> 5<br/>
<input type="radio" name="q2" value="6"> 6<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja3" class="questions3">
<span class="quest3">VW stands for ?</span><br/>
<input type="radio" name="q3" value="BMW" /> BMW <br/>
<input type="radio" name="q3" value="Volkswagen" class="correct" /> Volkswagen<br/>
<input type="radio" name="q3" value="Audi" /> Audi<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja4" class="questions4">
<span class="quest4">What year it is ?</span><br/>
<input type="radio" name="q4" value="2017" /> 2017<br/>
<input type="radio" name="q4" value="2015" /> 2015<br/>
<input type="radio" name="q4" value="2019" class="correct" /> 2019<br/>
<input id="bot-submit" type="submit" value="Submit" />
</div>
</div>
</form>
</div>

Change Tab Color when a Radio Button is already selected

I'm currently working on a Skill Test project that displays one question on each tab and the choices for answers are radio buttons. I want to change the color of the tab when a radio button is selected (when the user answers a question) so that it will indicate that the question was already answered. I hope someone can help me since Im new to this.. thank you so much! Here are my codes:
(I didnt included some parts of my codes since I dont see them related, and to make my question short)
Style:
div.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
div.tab button {
background-color: inherit;
float: left;
border: 1px solid #ccc;
outline: none;
cursor: pointer;
padding: 13px 12.62px;
transition: 0.3s;
font-size: 10px;
}
div.tab button:hover {
background-color: #ddd;
}
div.tab button.active {
background-color: #d6f5d6;
}
.tabcontent {
display: none;
border: 1px solid #ccc;
border-top: none;
}
Body:
<body onload="document.getElementById('defaultOpen').click();">
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
</script>
<div class="col-md-auto col-md-offset-1 col-centered">
<div class="panel panel-success">
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
</script>
<div class="tab">
<button class="tablinks active" type="button" onclick="openTab(event, 'q1')" id="defaultOpen"></button>
<button class="tablinks" type="button" onclick="openTab(event, 'q2')"></button>
<button class="tablinks" type="button" onclick="openTab(event, 'q3')"></button>
<button class="tablinks" type="button" onclick="openTab(event, 'q4')"></button>
<button class="tablinks" type="button" onclick="openTab(event, 'q5')"></button>
</div>
<?php if (mysqli_num_rows($result) > 0): ?>
<?php $index = 0; $num=0; ?>
<div id="q<?php echo ($index++); ?>" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[<?php echo $test_id;?>]" style="text-indent: 40px;"> <?php echo $num,'. ', $question; ?> </h3>
</tr>
<tr class="form-group">
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiona;?>"><?php echo $optiona;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionb;?>"><?php echo $optionb; ?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionc;?>"><?php echo $optionc;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiond;?>"><?php echo $optiond;?>
</label>
<br>
</tr>
</tbody>
</table>
<center>
<button class="btn btn-default btnBack" data-direction="back" type="button" onclick="openTab(event, 'q<?php echo ($index-=1); ?>')"><span class="glyphicon glyphicon-triangle-left"></span> Back</button>
<button class="btn btn-default btnNext" data-direction="next" type="button" onclick="openTab(event, 'q<?php echo ($index+=1); ?>')"><span class="glyphicon glyphicon-triangle-right"></span> Next</button>
</center>
<br>
</div>
<?php $num++; ?>
<?php endif ?>
</div>
</div>
</div>
</body>
I made an JSbin of your code:
https://jsbin.com/conuhow/edit?js,console,output
It has some changes (without the PHP part) so you can view.
Hope this helps! Have a good time!
Code Bellow:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Questions</title>
<script language="javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body onload="document.getElementById('defaultOpen').click();">
<style>
div.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
div.tab button {
background-color: inherit;
float: left;
border: 1px solid #ccc;
outline: none;
cursor: pointer;
padding: 13px 12.62px;
transition: 0.3s;
font-size: 10px;
}
div.tab button:hover {
background-color: #ddd;
}
div.tab button.active {
background-color: #d6f5d6 !important;
}
.input-style {
font-size: 18px;
text-indent: 70px;
}
.tabcontent {
display: none;
border: 1px solid #ccc;
border-top: none;
}
.btnSend {
background-color: rgba(94,191,79,1.00);
color: #fff;
border: 0px;
padding: 15px;
border-radius: 7px;
}
.tabchanged {
background-color: rgba(41,215,217,1.00) !important;
}
</style>
<script>
var questionSelected = 1;
var questionsReply = {
"question1" : 0,
"question2" : 0,
"question3" : 0,
"question4" : 0,
"question5" : 0
};
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
$(".answer").click(function(){
var clickedquestion = $(this).attr("question");
var clickedanswer = $(this).attr("answer");
if (clickedquestion == 1) { questionsReply.question1 = clickedanswer; }
else if (clickedquestion == 2) { questionsReply.question2 = clickedanswer }
else if (clickedquestion == 3) { questionsReply.question3 = clickedanswer }
else if (clickedquestion == 4) { questionsReply.question4 = clickedanswer }
else if (clickedquestion == 5) { questionsReply.question5 = clickedanswer }
});
});
function sendResult() {
alert("Object of Answers (PARSE JSON TO PHP BACK-END):", questionsReply);
}
function openTab(evt, tabName) {
questionSelected = tabName;
console.log("Tab: " + questionSelected);
console.log("Array of Answers :", questionsReply);
$(".tabcontent").hide();
$(".tablinks").removeClass('active');
$("#q"+tabName).show();
//COLORTABS before .active background;
colorTabs();
$(".tablinks[tabid="+questionSelected+"]").addClass("active");
evt.currentTarget.className += " active";
if (questionSelected = 1) {
if (questionsReply.question1 != 0) {
var answer_selected = questionSelected.question1;
if (answer_selected != undefined) {
$(".answer[question="+questionSelected+", answer="+answer_selected+"]").attr("checked ", "true");
}
}
}
else if (questionSelected = 2) {
if (questionsReply.question2 != 0) {
var answer_selected = questionSelected.question2;
if (answer_selected != undefined) {
alert("Entrou aqui - 2! " + answer_selected);
$(".answer[question="+questionSelected+", answer="+answer_selected+"]").attr("checked ", "true");
}
}
}
else if (questionSelected = 3) {
if (questionsReply.question3 != 0) {
var answer_selected = questionSelected.question3;
if (answer_selected != undefined) {
alert("Entrou aqui - 3! " + answer_selected);
$(".answer[question="+questionSelected+", answer="+answer_selected+"]").attr("checked ", "true");
}
}
}
else if (questionSelected = 4) {
if (questionsReply.question4 != 0) {
var answer_selected = questionSelected.question4;
if (answer_selected != undefined) {
alert("Entrou aqui - 4! " + answer_selected);
$(".answer[question="+questionSelected+", answer="+answer_selected+"]").attr("checked ", "true");
}
}
}
else if (questionSelected = 5) {
if (questionsReply.question5 != 0) {
var answer_selected = questionSelected.question5;
if (answer_selected != undefined) {
alert("Entrou aqui - 5! " + answer_selected);
$(".answer[question="+questionSelected+", answer="+answer_selected+"]").attr("checked ", "true");
}
}
}
}
function colorTabs() {
if (questionsReply.question1 != 0) { $(".tablinks[tabid='1']").addClass("tabchanged"); }
if (questionsReply.question2 != 0) { $(".tablinks[tabid='2']").addClass("tabchanged"); }
if (questionsReply.question3 != 0) { $(".tablinks[tabid='3']").addClass("tabchanged"); }
if (questionsReply.question4 != 0) { $(".tablinks[tabid='4']").addClass("tabchanged"); }
if (questionsReply.question5 != 0) { $(".tablinks[tabid='5']").addClass("tabchanged"); }
}
document.getElementById("defaultOpen").click();
</script>
<div class="col-md-auto col-md-offset-1 col-centered">
<div class="panel panel-success">
<div class="tab">
<button class="tablinks active" tabid="1" type="button" onclick="openTab(event, 1)" id="defaultOpen"></button>
<button class="tablinks" tabid="2" type="button" onclick="openTab(event, 2)"></button>
<button class="tablinks" tabid="3" type="button" onclick="openTab(event, 3)"></button>
<button class="tablinks" tabid="4" type="button" onclick="openTab(event, 4)"></button>
<button class="tablinks" tabid="5" type="button" onclick="openTab(event, 5)"></button>
</div>
<div id="q1" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[1]" style="text-indent: 40px;"></h3>
</tr>
<tr class="form-group">
<label class="radio-inline input-style"><input class="input-style answer" name="resposta1" type="radio" question="1" answer="1" value="a">Question 1 - Answer 01</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta1" type="radio" question="1" answer="2" value="b">Question 1 - Answer 02</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta1" type="radio" question="1" answer="3" value="c">Question 1 - Answer 03</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta1" type="radio" question="1" answer="4" value="d">Question 1 - Answer 04</label><br>
</tr>
</tbody>
</table>
<center>
<button class="btn btn-default btnNext" data-direction="next" type="button" onclick="openTab(event, 2)"><span class="glyphicon glyphicon-triangle-right"></span> Next</button>
</center>
<br>
</div>
<div id="q2" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[2]" style="text-indent: 40px;"></h3>
</tr>
<tr class="form-group">
<label class="radio-inline input-style"><input class="input-style answer" name="resposta2" type="radio" question="2" answer="1" value="a">Question 2 - Answer 01</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta2" type="radio" question="2" answer="2" value="b">Question 2 - Answer 02</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta2" type="radio" question="2" answer="3" value="c">Question 2 - Answer 03</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta2" type="radio" question="2" answer="4" value="d">Question 2 - Answer 04</label><br>
</tr>
</tbody>
</table>
<center>
<button class="btn btn-default btnBack" data-direction="back" type="button" onclick="openTab(event, 1)"><span class="glyphicon glyphicon-triangle-left"></span> Back</button>
<button class="btn btn-default btnNext" data-direction="next" type="button" onclick="openTab(event, 3)"><span class="glyphicon glyphicon-triangle-right"></span> Next</button>
</center>
<br>
</div>
<div id="q3" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[3]" style="text-indent: 40px;"></h3>
</tr>
<tr class="form-group">
<label class="radio-inline input-style"><input class="input-style answer" name="resposta3" type="radio" question="3" answer="1" value="a">Question 3 - Answer 01</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta3" type="radio" question="3" answer="2" value="b">Question 3 - Answer 02</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta3" type="radio" question="3" answer="3" value="c">Question 3 - Answer 03</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta3" type="radio" question="3" answer="4" value="d">Question 3 - Answer 04</label><br>
</tr>
</tbody>
</table>
<center>
<button class="btn btn-default btnBack" data-direction="back" type="button" onclick="openTab(event, 2)"><span class="glyphicon glyphicon-triangle-left"></span> Back</button>
<button class="btn btn-default btnNext" data-direction="next" type="button" onclick="openTab(event, 4)"><span class="glyphicon glyphicon-triangle-right"></span> Next</button>
</center>
<br>
</div>
<div id="q4" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[4]" style="text-indent: 40px;"></h3>
</tr>
<tr class="form-group">
<label class="radio-inline input-style"><input class="input-style answer" name="resposta4" type="radio" question="4" answer="1" value="a">Question 4 - Answer 01</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta4" type="radio" question="4" answer="2" value="b">Question 4 - Answer 02</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta4" type="radio" question="4" answer="3" value="c">Question 4 - Answer 03</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta4" type="radio" question="4" answer="4" value="d">Question 4 - Answer 04</label><br>
</tr>
</tbody>
</table>
<center>
<button class="btn btn-default btnBack" data-direction="back" type="button" onclick="openTab(event, 3)"><span class="glyphicon glyphicon-triangle-left"></span> Back</button>
<button class="btn btn-default btnNext" data-direction="next" type="button" onclick="openTab(event, 5)"><span class="glyphicon glyphicon-triangle-right"></span> Next</button>
</center>
<br>
</div>
<div id="q5" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[5]" style="text-indent: 40px;"></h3>
</tr>
<tr class="form-group">
<label class="radio-inline input-style"><input class="input-style answer" name="resposta5" type="radio" question="5" answer="1" value="a">Question 5 - Answer 01</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta5" type="radio" question="5" answer="2" value="b">Question 5 - Answer 02</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta5" type="radio" question="5" answer="3" value="c">Question 5 - Answer 03</label><br>
<label class="radio-inline input-style"><input class="input-style answer" name="resposta5" type="radio" question="5" answer="4" value="d">Question 5 - Answer 04</label><br>
</tr>
</tbody>
</table>
<center>
<button class="btn btn-default btnBack" data-direction="back" type="button" onclick="openTab(event, 4)"><span class="glyphicon glyphicon-triangle-left"></span> Back</button>
<button class="btn btn-default btnSend" data-direction="back" type="button" onclick="sendResult()"><span class="glyphicon glyphicon-triangle-left"></span> SEND</button>
</center>
<br>
</div>
</div>
</div>
</body>
</html>

How to show 1 answer at a time in a quiz

Right now after you click for example answer A and click submit, There appears some explanation after Answer A. And when you click answer B, explanation B pops up. But explanation A still remains. How to fix this ?
document.getElementById("form1").onsubmit = function(e) {
e.preventDefault();
variable = parseInt(document.querySelector('input[name = "variable"]:checked').value);
sub = parseInt(document.querySelector('input[name = "sub"]:checked').value);
con = parseInt(document.querySelector('input[name = "con"]:checked').value);
result = variable + sub + con;
document.getElementById("grade").innerHTML = result;
var result2 = "";
if (result == 0) {
result2 = "I don't think you studied."
};
if (result == 33) {
result2 = "You need to spend more time. Try again."
};
if (result == 66) {
result2 = "I think you could do better. Try again."
};
if (result == 99) {
result2 = "Excellent!"
};
document.getElementById("grade2").innerHTML = result2;
return false; // required to not refresh the page; just leave this here
} //this ends the submit function
function myFunction() {
var checked = document.querySelector("input[name = 'variable']:checked");
var value = checked.parentNode.lastChild.id;
var answer;
switch (value) {
case 'demo':
answer = "An octagon is an object with 8 sides to it";
break;
case 'demo2':
answer = "Leprosy is a chronic infection";
break;
case 'demo3':
answer = "Yes ! this is correct";
break;
}
checked.parentNode.lastChild.innerHTML = answer;
}
.quizbox {
width: 58%;
max-width: 950px;
border: 1px gray solid;
margin: auto;
padding: 10px;
border-radius: 10px;
border-width: 5px;
border-color: #00A7AE;
margin-top: 7%;
text-align: center;
position: relative;
background: #73B7DB;
}
.row {
text-align: left;
color: white;
margin-left: 10%;
}
span#demo, #demo2, #demo3 {
display: inline;
color: green;
margin-right: 30%;
float:right;
width:50%;
}
<div class="quizbox">
<!-- open main div -->
<h1>Quiz</h1>
<form id="form1" action=" ">
<div class="row"> <h3>Moths are a member of what order?</h3></div>
<div class="row">
<input name="variable" type="radio" value="0" />Octagon <span id="demo"></span></div>
<div> </div>
<div class="row">
<input name="variable" type="radio" value="0" />Leprosy <span id="demo2"></span></div>
<div class="row">
<input name="variable" type="radio" value="33" />Lepidoptera <span id="demo3"></span></div>
<div class="row"> <h3>Question 2</h3></div>
<div class="row">
<input name="sub" type="radio" value="33" />Answer 1 </div>
<div class="row">
<input name="sub" type="radio" value="0" />Answer 2</div>
<div class="row">
<input name="sub" type="radio" value="0" />Answer 3</div>
<div class="row"><h3>Question 3</h3></div>
<div class="row">
<input name="con" type="radio" value="0" />Answer 1</div>
<div class="row">
<input name="con" type="radio" value="33" />Answer 2</div>
<div class="row">
<input name="con" type="radio" value="0" />Answer 3</div>
<p> <input type="submit" onclick="myFunction()" value="Submit" /> </p>
</form>Your grade is: <span id="grade">__</span>
<p id="grade2"></p>
</div>
<!-- close quizbox div -->
<span>fdf</span> <span>fdf</span><span>fdf</span>
fd
hgf
<div> </div>

Change btn color when clicking menu checkbox option

I am trying to have a button change color when a user clicks one of the options from a menu listing. Is this possible?
For btn_clear, I would like the background-color to change automatically immediately to BLUE upon click of one of the menu options, and for btn_apply the same but color change to RED.
So for example, for category "Products" a user clicks "Alpha" and then the button color changes take effect automatically immediately.
Please see my FIDDLE... FIDDLE
(SA snippet doesnt seem to want to work... sorry).
$(".btn_clear").on('click', function (e) {
e.stopPropagation();
$(this).closest('.dropdown-menu').find('input[type="checkbox"]').prop('checked', false);
});
$('.dropdown-menu').click(function(e) {
e.stopPropagation();
});
$("checkbox").on("click", function(e) {
e.preventDefault();
var i = $("li").index( $(this).parent() );
if ( i === 1 ) {
$('btn_clear').css('background', 'blue');
} else if ( i === 2 ) {
$('btn_apply').css('background', 'red');
}
});
.scrollable-menu {
height: auto;
max-height: 200px;
overflow-x: hidden;
}
.checkbox :hover {
background-color:red;
cursor:pointer;
}
.div_form :hover {
background-color:green;
cursor:pointer;
}
.btn_clear {
float: right;
display: inline-block;
box-sizing: border-box;
width: 50%;
padding: 10px 29px;
text-align: center;
background-color:grey
}
.btn_apply {
float: left;
display: inline-block;
box-sizing: border-box;
width: 50%;
padding: 10px 17px;
text-align: center;
background-color:yellow
}
.checkbox label, .radio label {
min-height: 20px;
padding-left: 30px;
padding-right:30px;
margin-bottom: 0;
font-weight: 400;
cursor: pointer;
width: 100%;
}
.div_form {
position: absolute;
bottom: 0;
bottom: -70px
}
.btn {
border-radius:0;
margin-top:5px
}
.dropdown-menu {
border-radius:0;
border:5px solid blue
}
.typeahead {
width:90%;
margin-left:10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/umd/dropdown.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
<div class="btn-toolbar">
<!--Default buttons with dropdown menu-->
<div class="btn-group">
<button class="btn btn-primary" type="button">Products</button>
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" type="button"><span class="caret"></span></button>
<div class="dropdown-menu" style="margin-left: 2em">
<div style="position: relative;">
<div class=" scrollable-menu" style="margin-bottom: 70px;">
<input class="countries" placeholder="Countries" type="text"> <div class="checkbox">
<label><input value="" type="checkbox"> Alpha</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Beta
</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Gamma</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Delta</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Omega</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Koppa
</label>
</div>
<div class="div_form">
<span class="btn_apply">Apply</span> <span class="btn_clear">Clear</span>
</div>
</div>
</div>
</div>
</div><!--Success buttons with dropdown menu-->
<div class="btn-group">
<button class="btn btn-primary" type="button">Availability</button>
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" type="button"><span class="caret"></span></button>
<div class="dropdown-menu" style="margin-left: 2em">
<div style="position: relative;">
<div class=" scrollable-menu" style="margin-bottom: 70px;">
<input class="typeahead" placeholder="Search values" type="text"> <div class="checkbox">
<label><input value="" type="checkbox"> One</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Two
</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Nine</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Eight</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Seven</label>
</div>
<div class="checkbox">
<label><input value="" type="checkbox"> Fifteen
</label>
</div>
<div class="div_form">
<span class="btn_apply">Apply</span> <span class="btn_clear">Clear</span>
</div>
</div>
</div>
</div>
</div><!--Warning buttons with dropdown menu-->
</div>
Yes, it is possible http://www.bootply.com/rb3Uyw68Zg
but you have a few issues with your code, I added some "console.log" the see what was going on there
first you were missing a "." in your selectors, to change
if ( i === 1 ) {
$('btn_clear').css('background', 'blue');
} else if ( i === 2 ) {
$('btn_apply').css('background', 'red');
}
into
if ( i === 1 ) {
$('.btn_clear').css('background', 'blue');
} else if ( i === 2 ) {
$('.btn_apply').css('background', 'red');
}
also
var i = $("li").index( $(this).parent() );
is always resulting -1, so you never get into those ifs, you'll have to fix this line for your background color changes to get called.
this is the code after my changes http://www.bootply.com/rb3Uyw68Zg
EDIT
to restrict the handling of clicks per menu, you can use the descendant selector, so you should change:
$(".checkbox").on("click", function(e) {
into
$(".products .checkbox").on("click", function(e) {
that means, you will only handle clicks to checkboxes that are children of ".products" (you also have to add products class to your dropdown)
here's an updated example: http://www.bootply.com/QoIe6kIt2e
This will change the colors of both of the buttons when one option is selected:
$(".checkbox").on("click", function(e) {
$('.btn_clear').css('background-color', 'blue');
$('.btn_apply').css('background-color', 'red');
});
Snippet:http://www.bootply.com/0CQWCAtU2s

Categories