Essentially, I want one question to be displayed with several radio button options. When one button is clicked, a new question pops below the first (specific to the answer chosen) with a new set of radio buttons. When an answer from this set is clicked, another question pops below (specific to the answer chosen here) and so on and so forth. If the user decides to select any of the prior radio buttons I would like everything after that button (unrelated to the answer) to be hidden.
I end up with either all options selected at any time will stay on the page even when a different option is selected (the different option is simply added to the list...) Or, only the most recent question will stay on the page, making it impossible to choose differently on the prior questions...
Here is what I have right now:
$(document).ready(function(){
$("input[name$='group1']").click(function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
});
});
.desc { display: none; }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Basic jQuery Quiz Demo Page</title>
<link rel="Stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>Troubleshooting</h1>
<h2>What needs to be fixed?</h2>
<form>
<div><label><input type="radio" name="group1" value="in1">Internet</label></div>
<div><label><input type="radio" name="group1" value="tv1">TV</label></div>
<div><label><input type="radio" name="group1" value="ph1">Phone</label></div>
</form>
<div id="in1" class="desc">
<h3>Internet Troubleshooting</h3>
<h3>Are there lights on the router?</h3>
<form>
<div><label><input type="radio" name="group1" value="in2">Yes</label></div>
<div><label><input type="radio" name="group1" value="in3">No</label></div>
</form>
</div>
<div id="in2" class="desc">
<h3>Is the power light red?</h3>
<form>
<div><label><input type="radio" name="group1" value="in4">Yes</label></div>
<div><label><input type="radio" name="group1" value="in5">No</label></div>
</form>
</div>
<div id="in3" class="desc">
<h3>Is the router plugged in?</h3>
<form>
<div><label><input type="radio" name="group1" value="in6">Yes</label></div>
<div><label><input type="radio" name="group1" value="in7">No</label></div>
</form>
</div>
<div id="in4" class="desc">
<h3>Failing Device</h3>
<p>A red power light most likely indicates the device is not functioning properly. Contact your ISP.</p>
</div>
<div id="in6" class="desc">
<h3>Plug the router into another outlet. Is the power light on?</h3>
<form>
<div><label><input type="radio" name="group1" value="in4">Yes</label></div>
<div><label><input type="radio" name="group1" value="in5">No</label></div>
</form>
</div>
<div id="in7" class="desc">
<h3>Please plug in your router and try again once the router has fully started up. (Note: This process may take up to 5 minutes)</h3>
</div>
<div id="tv1" class="desc">
<h1>TV Troubleshooting</h1>
<form>
<div><label><input type="radio" name="group1" value="tv2">opt1</label></div>
<div><label><input type="radio" name="group1" value="tv3">opt2</label></div>
<div><label><input type="radio" name="group1" value="tv4">opt3</label></div>
</form>
</div>
<div id="ph1" class="desc">
<h1>Phone Troubleshooting</h1>
<form>
<div><label><input type="radio" name="group1" value="ph2">opt1</label></div>
<div><label><input type="radio" name="group1" value="ph3">opt2</label></div>
<div><label><input type="radio" name="group1" value="ph4">opt3</label></div>
</form>
</div>
</body>
</html>
The best way to do this would be to define your questions and answers in a separate Javascript file and dynamically generate the quiz form.
But say you didn't want to do that -- here's one way you could accomplish that with just your HTML (slightly tweaked) and Javascript:
$(document).ready(function(){
$("input[name$='group1']").click(function() {
var test = $(this).val();
if (test[2] == '1') {
// Check whether this is a top-level question, and if so,
// hide all the subquestions (and uncheck responses)
$('.desc').hide();
$('input').not('[value='+test+']').removeAttr('checked');
} else {
// Find the ID of this question
var parent_q = $($(this).parents('.desc')[0]).attr('id');
var type = parent_q.substring(0,2); // Get the type, such as "in"
var level = parent_q.substring(2); // Get the level, such as 1
$(".desc").each(function(elt_index, elt) {
// Hide each question/answer with either a different type or a higher ID.
var e_id = $(elt).attr('id');
if(e_id.substring(0,2) != type || e_id.substring(2) > level) {
$(elt).hide();
$(elt).children('input').removeAttr('checked');
}
});
}
$("#"+test).show();
});
});
.desc { display: none; }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Basic jQuery Quiz Demo Page</title>
<link rel="Stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>Troubleshooting</h1>
<h2>What needs to be fixed?</h2>
<form>
<div><label><input type="radio" name="group1" value="in1">Internet</label></div>
<div><label><input type="radio" name="group1" value="tv1">TV</label></div>
<div><label><input type="radio" name="group1" value="ph1">Phone</label></div>
</form>
<div id="in1" class="desc">
<h3>Internet Troubleshooting</h3>
<h3>Are there lights on the router?</h3>
<form>
<div><label><input type="radio" name="group1" value="in2">Yes</label></div>
<div><label><input type="radio" name="group1" value="in3">No</label></div>
</form>
</div>
<div id="in2" class="desc">
<h3>Is the power light red?</h3>
<form>
<div><label><input type="radio" name="group1" value="in8">Yes</label></div>
<div><label><input type="radio" name="group1" value="in5">No</label></div>
</form>
</div>
<div id="in3" class="desc">
<h3>Is the router plugged in?</h3>
<form>
<div><label><input type="radio" name="group1" value="in6">Yes</label></div>
<div><label><input type="radio" name="group1" value="in7">No</label></div>
</form>
</div>
<div id="in6" class="desc">
<h3>Plug the router into another outlet. Is the power light on?</h3>
<form>
<div><label><input type="radio" name="group1" value="in4">Yes</label></div>
<div><label><input type="radio" name="group1" value="in5">No</label></div>
</form>
</div>
<div id="in7" class="desc">
<h3>Please plug in your router and try again once the router has fully started up. (Note: This process may take up to 5 minutes)</h3>
</div>
<div id="in8" class="desc">
<h3>Failing Device</h3>
<p>A red power light most likely indicates the device is not functioning properly. Contact your ISP.</p>
</div>
<div id="tv1" class="desc">
<h1>TV Troubleshooting</h1>
<form>
<div><label><input type="radio" name="group1" value="tv2">opt1</label></div>
<div><label><input type="radio" name="group1" value="tv3">opt2</label></div>
<div><label><input type="radio" name="group1" value="tv4">opt3</label></div>
</form>
</div>
<div id="ph1" class="desc">
<h1>Phone Troubleshooting</h1>
<form>
<div><label><input type="radio" name="group1" value="ph2">opt1</label></div>
<div><label><input type="radio" name="group1" value="ph3">opt2</label></div>
<div><label><input type="radio" name="group1" value="ph4">opt3</label></div>
</form>
</div>
</body>
</html>
This should do it:
https://jsfiddle.net/csbnw5ne/2/
I hope the comments in the jsFiddle are clear.
I didn't have much time left so I had to rush it. It's a fairly simple solution:
You have to remember what boxes you opened and which ones you have to close. You have to find this out somehow, so I numbered the boxes with box-number.
Then, in jQuery I check for the box number containing the options. I proceed to close all boxes beyond the box that was just clicked in, but only if the previously opened box was an "earlier" box than the box that was just clicked in!
Then I simply open the required box without hiding all boxes.
Now all you have to do is make sure you sort them correctly. Make sure any "end" of the quiz is the last box and number them correctly. Keep them grouped together like you are now and it should work. It's not perfect, but it's as simple as I could think it up in a few minutes and it should work if you keep your html sorted.
Let me know if you have any more issues with this!
New HTML for when the jsFiddle goes out:
<h1>Troubleshooting</h1>
<h2>What needs to be fixed?</h2>
<form>
<div><label><input type="radio" name="group1" value="in1">Internet</label></div>
<div><label><input type="radio" name="group1" value="tv1">TV</label></div>
<div><label><input type="radio" name="group1" value="ph1">Phone</label></div>
</form>
<div id="in1" class="desc" data-box="1">
<h3>Internet Troubleshooting</h3>
<h3>Are there lights on the router?</h3>
<form>
<div><label><input type="radio" name="group1" value="in2">Yes</label></div>
<div><label><input type="radio" name="group1" value="in3">No</label></div>
</form>
</div>
<div id="in2" class="desc" data-box="2">
<h3>Is the power light red?</h3>
<form>
<div><label><input type="radio" name="group1" value="in4">Yes</label></div>
<div><label><input type="radio" name="group1" value="in5">No</label></div>
</form>
</div>
<div id="in3" class="desc" data-box="3">
<h3>Is the router plugged in?</h3>
<form>
<div><label><input type="radio" name="group1" value="in6">Yes</label></div>
<div><label><input type="radio" name="group1" value="in7">No</label></div>
</form>
</div>
<div id="in6" class="desc" data-box="4">
<h3>Plug the router into another outlet. Is the power light on?</h3>
<form>
<div><label><input type="radio" name="group1" value="in4">Yes</label></div>
<div><label><input type="radio" name="group1" value="in5">No</label></div>
</form>
</div>
<div id="in4" class="desc" data-box="5">
<h3>Failing Device</h3>
<p>A red power light most likely indicates the device is not functioning properly. Contact your ISP.</p>
</div>
<div id="in7" class="desc" data-box="6">
<h3>Please plug in your router and try again once the router has fully started up. (Note: This process may take up to 5 minutes)</h3>
</div>
<div id="tv1" class="desc" data-box="7">
<h1>TV Troubleshooting</h1>
<form>
<div><label><input type="radio" name="group1" value="tv2">opt1</label></div>
<div><label><input type="radio" name="group1" value="tv3">opt2</label></div>
<div><label><input type="radio" name="group1" value="tv4">opt3</label></div>
</form>
</div>
<div id="ph1" class="desc" data-box="8">
<h1>Phone Troubleshooting</h1>
<form>
<div><label><input type="radio" name="group1" value="ph2">opt1</label></div>
<div><label><input type="radio" name="group1" value="ph3">opt2</label></div>
<div><label><input type="radio" name="group1" value="ph4">opt3</label></div>
</form>
</div>
New javascript for when the jsfiddle goes out:
$(document).ready(function(){
var lastBoxOpened = 0;
$("input[name$='group1']").click(function() {
var boxNumber = parseInt($(this).parents('.desc').attr("data-box"));
//check if the data-box was succesfully retrieved. If not, first option chosen, reset all of it
if(isNaN(boxNumber)){
boxNumber = 0;
}
var test = $(this).val();
var target = $("#"+test)
var newBoxOpened = target.attr("data-box");
//check if the last opened box was an earlier one than the newly clicked one
if(lastBoxOpened > boxNumber){
//hide boxes beyond the one we opened now
$('.desc').each(function(){
//if box number is bigger than the currently clicked box, close them.
if($(this).attr("data-box") > boxNumber){
$(this).hide();
//uncheck the previously selected radio buttons in now hidden things
$('input', this).prop("checked", false);
}
});
}
//render target box
target.show();
//update last opened box to the newly opened one
lastBoxOpened = newBoxOpened;
});
});
Sidenote: I put the html for the in6 wrapper above the in4 wrapper, so that this outcome (which will never be revealed until the end of the quiz) will always stay on the bottom. Otherwise it would pop up above in6 instead of as an answer.
update: I have now also added the functionality of actually clearing previously selected radio buttons in boxes that get hidden! Just seemed less sloppy to me (Strange if the user has to click a selected box to see a result)
You have to use dynamic elements within your javascript that should link to only one div in your html. Here's an example that i have with a survey that i did. Not sure if you know, but the dynamic elements are the elements with $(<...>):
HTML:
<div id = "surveyDiv">
<ul class = "options">
<ul><input type="radio" id="v1" name="q" value=1>1</ul>
<ul><input type="radio" id="v2" name="q" value=2>2</ul>
<ul><input type="radio" id="v3" name="q" value=3>3</ul>
<ul><input type="radio" id="v4" name="q" value=4>4</ul>
<ul><input type="radio" id="v5" name="q" value=5>5</ul>
</ul>
<button id="next" type="button">Next</button>
</div>
Javascript:
$('#surveyTime').on('click', function(){
friend.name = $('#nameInput').val().trim();
$('.personalInfo').hide();
$('.survey').show();
});
//survey questions
var questions =
[{question: "You would know at least 2 songs at a Pearl Jam concert"},
{question: "You would dress up and dance all day Electric Zoo"},
{question: "You can tell the difference between Country Songs"},
{question: "You enjoy guitar solos"},
{question: "You have been or would go to Bonnaroo"},
{question: "You love Justin Bieber"},
{question: "You know who Public Enemy is"},
{question: "You appreciate Miles Davis"},
{question: "You like and dance/or would like to learn to dance salsa"},
{question: "You're one of those people that says you like all music"}];
//starting with question as 0 since array starts at 0
var questionNumber = 0;
//creates each question one at a time
function createQuestion(index){
var newDiv = $('<div>', {
id: 'current'
});
var newP = $('<p>');
newP.append(questions[index].question);
newDiv.append(newP);
return newDiv;
};
//appends the next question and removes the previous question
//also removes the display of the questions once done
function displayNext(){
$('#current').remove();
if(questionNumber < questions.length){
var nextQuestion = createQuestion(questionNumber);
$('#question').append(nextQuestion);
} else {
$('.survey').hide();
$('#submitButton').show();
var newDiv2 = $('<div>');
var final = $('<h2>Thank You For Taking This Survey. Please Press Submit Button To Meet Your Match</h2>');
newDiv2.append(final);
$('.thankYou').append(newDiv2);
}
}
Related
so currently I am trying to display different images for each radio button checked. each question has two answers each and the users are to choose between either and in the end, there is a submit button (like any other form). I want to be able to display images for each certain checked radio button. so for example, if each of the question they picked the first answer and press submit, it would display picture 1, if they were to pick the first answer for all besides the last question, it would display a different picture, and so on (so for each combination of results = different picture). thanks
function myFunction() {
var tops = document.getElementsByName('tops');
var str =' ';
for (i = 0; i < 20; i++) {
if (tops[i].checked === true) {
str += tops[i].value + " ";
}
}
alert(str);
}
<!DOCTYPE html>
<html>
<head>
<title> Quiz Yourself! </title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body class="deer">
<h1 style="font-size: 120px; text-align: center; border: 3px solid black; background-color: white;"> Quiz Yourself! </h1>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Solid_white.svg/2000px-Solid_white.svg.png" class="pop">
<h3> 1. Shows or Movies? </h3>
<form class="ok">
<input type="radio" name="tops" value="Shows" checked> Shows <br>
<input type="radio" name="tops" value="Movies"> Movies <br>
</form>
<h3> 2. Apple or Windows? </h3>
<form class="ok">
<input type="radio" name="tops" value="Apple" checked> Apple <br>
<input type="radio" name="tops" value="Windows"> Windows <br>
</form>
<h3> 3. Pink or Blue? </h3>
<form class="ok">
<input type="radio" name="tops" value="Pink" checked> Pink <br>
<input type="radio" name="tops" value="Blue"> Blue <br>
</form>
<h3> 4. Basketball or Football? </h3>
<form class="ok">
<input type="radio" name="tops" value="Basketball" checked> Basketball <br>
<input type="radio" name="tops" value="Football"> Football <br>
</form>
<h3> 5. Phone Call or Texting Type of Person? </h3>
<form class="ok">
<input type="radio" name="tops" value="Phone Call" checked> Phone Call <br>
<input type="radio" name="tops" value="Texting"> Texting <br>
</form>
<h3> 6. Cake or Pie? </h3>
<form class="ok">
<input type="radio" name="tops" value="Cake" checked> Cake <br>
<input type="radio" name="tops" value="Pie"> Pie <br>
</form>
<h3> 7. Big Party or Small Gathering? </h3>
<form class="ok">
<input type="radio" name="tops" value="Big Party" checked> Big Party <br>
<input type="radio" name="tops" value="Small Gathering"> Small Gathering <br>
</form>
<h3> 8. Sneakers or Sandals? </h3>
<form class="ok">
<input type="radio" name="tops" value="Sneakers" checked> Sneakers <br>
<input type="radio" name="tops" value="Sandals"> Sandals <br>
</form>
<h3> 9. Gold or Silver? </h3>
<form class="ok">
<input type="radio" name="tops" value="Gold" checked> Gold <br>
<input type="radio" name="tops" value="Silver"> Silver <br>
</form>
<h3> 10. Pen or Pencil? </h3>
<form class="ok">
<input type="radio" name="tops" value="Pen" checked> Pen <br>
<input type="radio" name="tops" value="Pencil"> Pencil <br>
</form>
<br>
<br>
<br>
<br>
<br>
<br>
<button onclick="myFunction();return false;" class="yes"> Submit </button>
</body>
</html>
I assumed that all of the question can only have 2 choices.
I also assumed that you want to display the image in a <img src='...' /> dom element.
In that case, I have modified your code to work as follows:
a- begin with str empty string
b- check the first question, the first option. If it is checked, append a to str. If it is unchecked then append b. There is no need to check the second option. So, lets skip it
c- loop until all question have been iterated (tops.length) not just '20'. You might decided to add more or remove questions. So it is better to rely on tops.length.
d- Append a proper image file extension to the string obtained above. ie: .png/.jpg/etc.
e- set the property src of the result image as described above.
var results = {
"aaaaaaaaaa":"https://i.ytimg.com/vi/EDzLx3hkli0/maxresdefault.jpg",
"aaaaaaaaab":"https://cdn.pixabay.com/photo/2017/07/28/23/34/fantasy-picture-2550222_960_720.jpg",
"bbbbbbbbbb":"http://your.image.link/here.png"
}
// you need to fill the other values.
function myFunction() {
var tops = document.getElementsByName('tops');
var str ='';
// assuming each question only has 2 choices, we can
// safely iterate through all question by evaluating
// the first option of each question and skipping the
// second option, since, if the first option is checked
// then the other option is not, and vice versa
for (i = 0; i < tops.length; i+=2) {
str += (tops[i].checked)? 'a':'b'; // I choose 'a' for checked, and 'b' for unchecked
}
// after the loop, if all questions were answered by the first option, you will get
// 'aaaaaaaaaa' and if all of them selected the second option, you will get 'bbbbbbbbbb'
var link = results[str]; // lookup for the image path
var img = document.getElementById("result");
img.alt = link;
img.src = link;
alert(str + "=" + link);
}
<!DOCTYPE html>
<html>
<head>
<title> Quiz Yourself! </title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body class="deer">
<h3> 1. Shows or Movies? </h3>
<form class="ok">
<input type="radio" name="tops" value="Shows" checked> Shows <br>
<input type="radio" name="tops" value="Movies"> Movies <br>
</form>
<h3> 2. Apple or Windows? </h3>
<form class="ok">
<input type="radio" name="tops" value="Apple" checked> Apple <br>
<input type="radio" name="tops" value="Windows"> Windows <br>
</form>
<h3> 3. Pink or Blue? </h3>
<form class="ok">
<input type="radio" name="tops" value="Pink" checked> Pink <br>
<input type="radio" name="tops" value="Blue"> Blue <br>
</form>
<h3> 4. Basketball or Football? </h3>
<form class="ok">
<input type="radio" name="tops" value="Basketball" checked> Basketball <br>
<input type="radio" name="tops" value="Football"> Football <br>
</form>
<h3> 5. Phone Call or Texting Type of Person? </h3>
<form class="ok">
<input type="radio" name="tops" value="Phone Call" checked> Phone Call <br>
<input type="radio" name="tops" value="Texting"> Texting <br>
</form>
<h3> 6. Cake or Pie? </h3>
<form class="ok">
<input type="radio" name="tops" value="Cake" checked> Cake <br>
<input type="radio" name="tops" value="Pie"> Pie <br>
</form>
<h3> 7. Big Party or Small Gathering? </h3>
<form class="ok">
<input type="radio" name="tops" value="Big Party" checked> Big Party <br>
<input type="radio" name="tops" value="Small Gathering"> Small Gathering <br>
</form>
<h3> 8. Sneakers or Sandals? </h3>
<form class="ok">
<input type="radio" name="tops" value="Sneakers" checked> Sneakers <br>
<input type="radio" name="tops" value="Sandals"> Sandals <br>
</form>
<h3> 9. Gold or Silver? </h3>
<form class="ok">
<input type="radio" name="tops" value="Gold" checked> Gold <br>
<input type="radio" name="tops" value="Silver"> Silver <br>
</form>
<h3> 10. Pen or Pencil? </h3>
<form class="ok">
<input type="radio" name="tops" value="Pen" checked> Pen <br>
<input type="radio" name="tops" value="Pencil"> Pencil <br>
</form>
<br>
<br>
<img id="result" alt="Result Image here" text="Result Image Here" />
<br>
<br>
<br>
<br>
<button onclick="myFunction();return false;" class="yes"> Submit </button>
</body>
</html>
I'm creating a quiz with JavaScript where I'm trying to use the jQuery to make 1 question appear at a time. I was able to get the html to show only one question on the page, by hiding the other elements, but for some reason I can't get the next sibling to show.
The jQuery API Documentation says the next() method reaches for the sibling element, but I’m not sure where the problem is.
My jQuery code is.
function main()
{
$('.slide').hide();
$('.active-slide').show();
var currentSlide = $('.active-slide')
var nextSlide = currentSlide.next();
$('.btnNext').click(function() {
currentSlide.removeClass('active-slide');
nextSlide.addClass('active-slide');
})
}
$(document).ready(main);
My HTML is.
<div class="slide active-slide">
<h3>Question 1: Answer is A! </h3>
<input type="radio" name="q1" value="correct">A</input><br>
<input type="radio" name="q1" value="incorrect">B</input><br>
<input type="radio" name="q1" value="incorrect">C</input><br>
<input type="radio" name="q1" value="incorrect">D</input>
<input type="button" class="btnNext" value="Next">
</div>
<div class="slide">
<h3>Question 2: Answer is B! </h3>
<input type="radio" name="q2" value="incorrect">A</input><br>
<input type="radio" name="q2" value="correct">B</input><br>
<input type="radio" name="q2" value="incorrect">C</input><br>
<input type="radio" name="q2" value="incorrect">D</input>
<input type="button" class="btnNext" value="Next">
</div>
The console on Chrome shows no errors which makes it harder to find.
Thanks for any help.
The first issue is the result of a jQuery selector is not live meaning if the selector properties of an element changes the cached object will not get updated. So you need to find the active slide inside the event handler.
The second issue could be related to css, since you are using hide() to hide the element, it will be using an inline display rule, but to show the element back you are only setting the active-slide class which might be having a lower order rule.
function main() {
$('.btnNext').click(function() {
var currentSlide = $('.active-slide').removeClass('active-slide');
currentSlide.next().addClass('active-slide');
})
}
$(document).ready(main);
.slide {
display: none;
}
.slide.active-slide {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slide active-slide">
<h3>Question 1: Answer is A! </h3>
<input type="radio" name="q1" value="correct">A
<br>
<input type="radio" name="q1" value="incorrect">B
<br>
<input type="radio" name="q1" value="incorrect">C
<br>
<input type="radio" name="q1" value="incorrect">D
<input type="button" class="btnNext" value="Next">
</div>
<div class="slide">
<h3>Question 2: Answer is B! </h3>
<input type="radio" name="q2" value="incorrect">A
<br>
<input type="radio" name="q2" value="correct">B
<br>
<input type="radio" name="q2" value="incorrect">C
<br>
<input type="radio" name="q2" value="incorrect">D
<input type="button" class="btnNext" value="Next">
</div>
Your problem is that you only run the jQuery hide and show functions once; changing the classes of your divs isn't going to run that code again. Your jQuery needs to do something like this JSFiddle.
This way, the shown div is updated each time the classes are changed.
I'm using Javascript and radio buttons for the first time.
I need to know how to assign the script to each radio button that is selected? there seem to be a few ways of doing this and its just getting confusing!
Each question has 4 radio buttons to select from and I need to gather the answers at the end!
Any help appreciated
Just add an event listener to the radio buttons and maintain a mapping where you could store all your answers to.
let answers = {}
$('input[type=radio]').on('click', function (event) {
let question = event.currentTarget.name
let answer = event.currentTarget.value
answers[question] = answer
document.getElementById('result').innerHTML = JSON.stringify(answers, null, 2)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question-block">
<div class="question">
1. Which one is the biggest?
</div>
<div class="answers">
<form>
<input type="radio" name="1" value="1" checked> Elephant<br>
<input type="radio" name="1" value="2"> Whale<br>
<input type="radio" name="1" value="3"> Giraffe
</form>
</div>
</div>
<div class="question-block">
<div class="question">
2. Which one is the smallest animal?
</div>
<div class="answers">
<form>
<input type="radio" name="2" value="1" checked> Bacteria<br>
<input type="radio" name="2" value="2"> Virus<br>
<input type="radio" name="2" value="3"> Ant
</form>
</div>
</div>
<div id="result">
</div>
I'm trying to create a form with 10+ questions on it.
Each question with have three answer options, "Yes" "No" "Not applicable" which are chosen via radio buttons.
When "No" is selected a div is shown with additional information, this would be applicable for each question.
Not being great at Javascript I consulted Stack Overflow, found something and have failed miserably to amend it:
<script type="text/javascript">
function yesnoCheck() {
if (document.getElementById('noCheck').checked) {
document.getElementById('ifNo').style.display = 'block';
}
else document.getElementById('ifNo').style.display = 'none';
}
</script>
<p>Question 1</p>
<input type="radio" onclick="javascript:yesnoCheck();" name="q1" id="yesCheck"> Yes <br>
<input type="radio" onclick="javascript:yesnoCheck();" name="q1" id="noCheck"> No <br>
<input type="radio" onclick="javascript:yesnoCheck();" name="q1" id="naCheck"> Not applicable <br>
<div id="ifNo" style="display:none">
<p>Recommendation goes here</p>
</div>
<h2>Section header</h2>
<p>Question 2</p>
<input type="radio" onclick="javascript:yesnoCheck();" name="q2" id="yesCheck"> Yes <br>
<input type="radio" onclick="javascript:yesnoCheck();" name="q2" id="noCheck"> No <br>
<input type="radio" onclick="javascript:yesnoCheck();" name="q2" id="naCheck"> Not applicable <br>
<div id="ifNo" style="display:none">
<p>Recommendation goes here</p>
</div>
<p>Question 3</p>
<input type="radio" onclick="javascript:yesnoCheck();" name="q3" id="yesCheck"> Yes <br>
<input type="radio" onclick="javascript:yesnoCheck();" name="q3" id="noCheck"> No <br>
<input type="radio" onclick="javascript:yesnoCheck();" name="q3" id="naCheck"> Not applicable <br>
<div id="ifNo" style="display:none">
<p>Recommendation goes here</p>
</div>
This only works on the first question but not the others.
The intention is for this to go in a rails app and the number of questions could be large (more than 10) so was trying to create a short piece of code that would work on all questions.
Any help, from someone who knows what they're talking about (i.e. not me) would be extremely appreciated.
Do not use same id more than once. Here https://jsfiddle.net/o2kdb8ej/ you can find simple solution using jQuery, without any ids specified applicable for any number of questions. The main idea is to specify value for each radio button, handling change event for each radio button on the page, and in that handler check its value, and according to its value hide or show specified p element.
Is not valid html to have more than one element with the same id. You have multiple elements with id id=noCheck. When javascript code is executed the function getElementById() is looking for a single element, and returns the first one, that's why only the first div is showing.
You could assign the same name to every "No" radiobutton and use getElementsByName() instead. This returns a collection of elements, and then you could iterate over them to show all divs that must be shown.
Using same id for different elements in a html code is a bad way. You need to create different id's for different questions like:
<p>Question 1</p>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q1" id="yesCheck1"> Yes <br>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q1" id="noCheck1"> No <br>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q1" id="naCheck1"> Not applicable <br>
<div id="ifNo1" style="display:none">
<p>Recommendation goes here</p>
<h2>Section header</h2>
<p>Question 2</p>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q2" id="yesCheck2"> Yes <br>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q2" id="noCheck2"> No <br>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q2" id="naCheck2"> Not applicable <br>
<div id="ifNo2" style="display:none">
<p>Recommendation goes here</p>
<p>Question 3</p>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q3" id="yesCheck3"> Yes <br>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q3" id="noCheck3"> No <br>
<input type="radio" onclick="javascript:yesnoCheck(this.id);" name="q3" id="naCheck3"> Not applicable <br>
<div id="ifNo3" style="display:none">
<p>Recommendation goes here</p>
</div>
now in your javascript code:
function yesnoCheck() {
newId = id.split('k')[1]; //this will give 2 in "q2" (splitting)
var noCheck = "noCheck"
newNoCheck = noCheck.concat(newId); //if the newId is 2 then it will be "noCheck2"
var ifNo = "ifNo"
newifNo = ifNo.concat(newId); //if the newId is 2 then it will be "ifNo2"
if (document.getElementById(newNoCheck).checked) {
document.getElementById(newifNo).style.display = 'block';
}
else document.getElementById(newifNo).style.display = 'none';
}
You can find the working jsfiddle here
I have the following code in an html page:
<script type="text/javascript">
function industry(industryid)
{
if(industryid==0)
{
document.getElementById("SubIndustry").style.visibility="Hidden";
}
else
{
document.getElementById("SubIndustry").style.visibility="Visible";
}
}
</script>
This code is used here:
<div class="Question">
2. What is the primary nature of your business?
</div>
<div class="Answer">
<input type="radio" name="q2" class="Button" value="1-1" onchange='industry(0)' />
Manufacturing/Logistics
<br />
<input type="radio" name="q2" class="Button" value="1-2" onchange='industry(0)' />
Government/Schools
<br />
<input type="radio" name="q2" class="Button" value="1-3" onchange='industry(1)' />
Commercial/Service/Medical/Retail/Other
</div>
<div id="SubIndustry">
<div class="Question">
Services Sub Industry
</div>
<div class="Answer">
<input type="radio" name="q2-1" class="Button" value="135-55" />
Healthcare
<br />
<input type="radio" name="q2-1" class="Button" value="135-56" />
Other
</div>
</div>
Essentially this is what is supposed to happen: the SubIndustry div starts out invisible, and when someone selects the third industry option "Commercial/Service/Medical/Retail/Other" then the SubIndustry div appears. If they click off of the third industry it disappears.
This is how it's working in Firefox, but in IE8 it's not. It's acting like it's a "turn" behind. so when I click on the third industry, nothing happens, but if i click of then SubIndustry shows up. If I then click away it disappears again.
So, why is this working different in IE8 than Firefox?
I think it must be some bug because once you select the third option it is not making div visible but the very time you click outside somewhere else the div shows up!!!!!
I have modified the code and it works:-
<div class="Answer">
<input type="radio" name="q2" class="Button" value="1-1" onclick="industry(0)" />
Manufacturing/Logistics
<br />
<input type="radio" name="q2" class="Button" value="1-2" onclick="industry(0)" />
Government/Schools
<br />
<input type="radio" name="q2" class="Button" value="1-3" onclick="industry(1)" />
Commercial/Service/Medical/Retail/Other
</div>