Utilizing Radio Buttons for displaying or hiding nested div elements

My goal is to create a dynamic quiz where one question is displayed with multiple radio button options. When a user selects an answer, a new question related to that answer appears below with its set of radio buttons. This process continues for each subsequent answer chosen.

I'm facing an issue where either all selected options remain visible on the page at all times, or only the most recent question stays visible, making it impossible to revisit earlier questions and change answers.

Currently, my code looks like this:

$(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">
... <!-- Content for Internet Troubleshooting -->
</div>

<div id="in2" class="desc">
... <!-- Additional content based on previous answer in the Internet category -->
</div>

<div id="tv1" class="desc">
... <!-- TV Troubleshooting content -->
</div>

<div id="ph1" class="desc">
... <!-- Phone Troubleshooting content -->
</div>

</body>
</html>

Answer №1

If you prefer not to define your questions and answers in a separate Javascript file and dynamically generate the quiz form, there is an alternative approach using just HTML (with some modification) 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>

Answer №2

Here is the solution you need: https://jsfiddle.net/csbnw5ne/2/

I have provided clear comments in the jsFiddle, even though I had to rush due to time constraints. The solution is quite straightforward:

To successfully navigate this quiz, you must keep track of the boxes opened and closed. I assigned numbers to each box using box-number. Using jQuery, I identify which box contains the options based on the box number clicked. I then close all subsequent boxes only if the previously opened box was "earlier" than the current one. Finally, I open the required box without hiding all other boxes.

All you have to do is ensure proper sorting of the boxes. Number them correctly, group them logically as you are doing now, and place any quiz-ending content at the end. Following these simple guidelines should make the solution work. While not perfect, it's a quick and effective approach that should function with well-organized HTML.

If you encounter further issues, please let me know! Below is the updated HTML in case the link to jsFiddle expires:

<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>
... (Remaining structure of the HTML) ... 

Below is the new JavaScript code for when the jsFiddle link is no longer available:

$(document).ready(function(){ 
    var lastBoxOpened = 0;

    $("input[name$='group1']").click(function() {
        var boxNumber = parseInt($(this).parents('.desc').attr("data-box"));

        if(isNaN(boxNumber)){
         boxNumber = 0;
        }

        var test = $(this).val();
        var target = $("#"+test)
        var newBoxOpened = target.attr("data-box");

        if(lastBoxOpened > boxNumber){
         $('.desc').each(function(){
          if($(this).attr("data-box") > boxNumber){
          $(this).hide();
          $('input', this).prop("checked", false);
          }
         });
        }
        
         target.show();
         lastBoxOpened = newBoxOpened;
    }); 
});

Note: I arranged the HTML for the in6 container before in4 to ensure that the final outcome remains hidden until the end of the quiz. This prevents it from displaying prematurely above in6. Additionally, I added functionality to uncheck selected radio buttons in hidden boxes for a more polished user experience.

Update: Radio buttons in hidden boxes will now automatically clear upon closing, enhancing overall usability and clarity.

Answer №3

Creating dynamic elements in JavaScript that link to a single div within the HTML is crucial. Here's an example from a survey I conducted, showcasing the use of dynamic elements denoted by $(<...>):

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);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Overlapping containers

Recently, I attempted to implement a Bootstrap 4.1 theme into my yii2 project. However, I encountered an issue where the containers were overlapping by about half of their width. Surprisingly, the classes I used are directly from the bootstrap framework. H ...

Arranging RGB values in Javascript

I am interested in using javascript/jquery to organize an array of rgba values based on the colors of the visible spectrum. My goal is to have similar shades grouped together. Is there a specific plugin that can assist with this task, or what would be the ...

Exploring the values of data in c3js through data events

Is there a way to extract values from the Company data array within the onclick event? Currently, using the api functions only allows access to the Users array. var chartCompany = c3.generate({ bindto: '#users-chart', data: { ...

Tips for finding a duplicate button on a webpage with Protractor

After searching extensively, I am still struggling to find a way to locate a specific button on a webpage that lacks a unique identifier in the HTML. There are three buttons on the page, and the one I need to identify is the second one. Despite trying vari ...

Tips for automatically populating select options using AJAX with JSON information?

I have the following code in my controller: <?php class Cat_cntrl extends CI_controller{ public function __construct(){ parent::__construct(); $this->load->model('cat_model' ...

Any ideas on how to fix the bug that pops up when I launch my website for the very first time?

After successfully getting my website up and running, I noticed a tiny glitch that appears the first time it's opened. You can view the site here: www.voip-account.com This is not built using a WordPress theme; it's purely made with HTML and CSS ...

Creating a multi-dimensional array in order to store multiple sets of data

To generate a multidimensional array similar to the example below: var serviceCoors = [ [50, 40], [50, 50], [50, 60], ]; We have elements with latitude and longitude data: <div data-latitude="10" data-longitude="20" clas ...

Choosing read-only text fields using JQuery

I am working on an ASP.NET MVC project and I am looking to select all text boxes with the "readOnly" attribute on the current page. Once identified, I want to trigger a modal jQuery dialog on keypress for each of these disabled text boxes. Any suggestion ...

Positioning the div to align perfectly alongside the list items

My current objective involves dynamically creating div elements and populating them with items. A working demo of my progress can be found by following this link. The issue at hand is that the newly created div does not appear in the desired location, but ...

What steps should I take to either combine my two functions in my script or ensure they are executed in a specific sequence?

I'm attempting to incorporate a script into an HTML file (based on the solution provided by "skara9" in this post) and customize it to suit my requirements. However, I'm struggling to figure out how to make it work as intended. The script consis ...

The value of a variable decreases upon being utilized in an Ajax API call

My tempid variable seems to lose some of its values when passed into the second API call. Despite logging the variable to console (console.log(tempid)) where it appears fine, once placed in the API call it only retains some of its value. I'm uncertain ...

Utilizing webpack to extract CSS from SCSS files

I've been working on integrating webpack into my asp.net mvc core project. While I've successfully bundled js files, I'm facing an issue with extracting css from scss files. var path = require('path'); var extractTextPlugin = requ ...

Issues with rotating the camera in three.js are causing functionality problems

I have been working on a code snippet to rotate my camera around the x-axis within a three.js environment: var cameraOrginX = 0, cameraOrginY = 0, cameraOrginZ = 0; var cameraEndX = 0, cameraEndY = 0, cameraEndZ = 1000; var angle = 0; function initialize ...

Using jQuery: how can we animate an upward movement?

I currently have a vertical list of DIVs and I am able to use the .fadeOut() method to remove one of the middle DIVs. However, I am unsure how to generate a slow move-up effect for the remaining DIVs below the deleted one. Any advice on achieving this? ...

jQuery's $.ajax method no longer supports XHR

My current code looks like this: $.ajax(options) .then(function (response) { // success }, function (response, a, b) { // fail }) .always(function (output, status, xhr) { // xhr is always null here }); In the p ...

Enhance my code to eliminate repetitive elements

Check out this unique plant array: export const uniquePlants = [ { name: 'monstera', category: 'classique', id: '1ed' }, { name: 'ficus lyrata&ap ...

Guide on how to retrieve a response from an API Route and integrate it into the client side of the app router within Next.js

Transitioning from Next.js 12 to 13 has been quite perplexing, especially when it comes to handling JSON data. Every time I attempt a fetch request, I find myself needing to refer back to documentation due to the confusion surrounding JSON. Is there anyone ...

Continuously I am being informed that the value is null

Check out this code snippet: var Ribbon = /** @class */ (function () { function Ribbon(svg) { // Code here... } Ribbon.prototype.init = function() { // Initialization code here... }; Ribbon.prototype.updateR ...

Using Javascript to delete an HTML list

Currently, I am working on a webpage that includes notifications along with options to mark them as read individually or all at once. However, when attempting to use my loop function to mark all notifications as read, I noticed an issue. let markAllAsRead ...

Explore the search trees feature in d3 v5 to easily navigate and locate nodes within the tree structure. Highlight

For a while, I've been utilizing the CollapsibleTree Search by Patrick Brockmann with d3 v3.5. This search function fills a Select2 with tree leaves that can be used to locate and highlight a specific leaf node in red. Currently, I am attempting to m ...