1

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>
Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94

3 Answers3

0

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>
Christian Ternus
  • 8,406
  • 24
  • 39
  • The title of the page is `Basic jQuery Quiz Demo Page`. I feel like this is quite complicated for basic jQuery. Could you simplify it? – NoobishPro Aug 21 '16 at 02:35
0

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)

NoobishPro
  • 2,539
  • 1
  • 12
  • 23
  • 1
    This HTML is invalid; custom attributes (if used) are required to begin with `data-` to be valid. See [the W3C spec](https://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) and http://stackoverflow.com/questions/992115/custom-attributes-yea-or-nay. – Christian Ternus Aug 21 '16 at 02:39
  • 1
    (Otherwise, using custom attributes is definitely the way to go; it's really a choice of what new complexities you want to introduce.) Oh, and could you include the HTML here, since if the JSFiddle goes out the edits you made will be lost? – Christian Ternus Aug 21 '16 at 02:42
  • @ChristianTernus you are completely right. I have no clue what I was thinking at that point (It's 5 am and I'm kind of drunk right now.) -- I fixed the custom attributes, updated the jsfiddle and added the html. Thank you! – NoobishPro Aug 21 '16 at 02:48
-1

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);
    }
}
  • I disagree with this answer. Posting my answer in a few minutes. As the title is "A simple jQuery quiz" I don't think writing it entirely in javascript is the desired solution. – NoobishPro Aug 21 '16 at 02:17