"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions.

Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description will be displayed. Once the user answers the question, the current question will be hidden, and the next question will appear. This process continues until all the questions are answered.

Here is an example of my HTML structure:

<div class="container">
<form>
    <div id="q-1" class="question-group row">
        <div class="question-wrap">
            <p>question 1?</p>
            <label class="radio-inline">
                <input type="radio" name="q1" value="yes"> Yes
            </label>
            <label class="radio-inline">
                <input type="radio" name="q1" value="no"> No
            </label>
        </div>
        <div id="q1-yes" class="reason-wrap">
            <div class="reason">
                <h2><span class="number">1</span>reason 1</h2> 
            </div>
            <div class="reason-desc">
                <p>description</p>                    
            </div>
        </div>
        <div id="q1-no" class="reason-wrap">
            <div class="reason">
                <h2><span class="number">1</span>reason 1</h2> 
            </div>
            <div class="reason-desc">
                <p>description</p>                    
            </div>
        </div>
    </div>
    <div id="q-2" class="question-group row">
        <div class="question-wrap">
            <p>question 2?</p>
            <label class="radio-inline">
                <input type="radio" name="q2" value="yes"> Yes
            </label>
            <label class="radio-inline">
                <input type="radio" name="q2" value="no"> No
            </label>
        </div>
        <div id="q2-yes" class="reason-wrap">
            <div class="reason">
                <h2><span class="number">2</span>reason 2</h2> 
            </div>
            <div class="reason-desc">
                <p>description</p>                    
            </div>
        </div>
        <div id="q2-yes" class="reason-wrap">
            <div class="reason">
                <h2><span class="number">2</span>reason 2</h2> 
            </div>
            <div class="reason-desc">
                <p>description</p>                    
            </div>
        </div>
    </div>
</form>
</div>

Below is my JavaScript/jQuery code. There's a small part that I'm struggling with, which I have commented in the code snippet:

$('input[type="radio"]').click(function() {
   var desc = ('#' + $(this).attr("name") + '-' + $(this).val()); // match div to display for this question
   $(desc).toggle(); // show div for this question
   $(this).closest('.question-wrap').hide(); // hide this question
   $(this).parent().next('.question-wrap').show(); // show next question [not working]
   //??? hide only the .reason-desc that is currently showing when the next question is answered
});

For a live demo, you can visit: http://codepen.io/anon/pen/XMJZLK

Answer №1

It seems like this could be what you're searching for - my attempt at it is below:

$('input[type="radio"]').click(function() {
  var desc = ('#' + $(this).attr("name") + '-' + $(this).val()); //matching div to display for this question 
  $(desc).toggle(); //show div for this question
  $(this).closest('.question-wrap').hide()
    .parent().next().show().end().prev().find('.reason-desc').hide()
});
.question-group:not(:first-of-type) {
  display: none;
}

.reason-wrap {
  display: none;
  margin-bottom: 10px;
}

.reason h2 {
  font-size: 24px;
}

.reason-desc p {
  font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <form>
    <div id="q-1" class="question-group row">
      <div class="question-wrap">
        <p>question 1?</p>
        <label class="radio-inline">
                <input type="radio" name="q1" value="yes"> Yes
            </label>
        <label class="radio-inline">
                <input type="radio" name="q1" value="no"> No
            </label>
      </div>
      <div id="q1-yes" class="reason-wrap">
        <div class="reason">
          <h2><span class="number">1</span>reason 1</h2>
        </div>
        <div class="reason-desc">
          <p>description</p>
        </div>
      </div>
      <div id="q1-no" class="reason-wrap">
        <div class="reason">
          <h2><span class="number">1</span>reason 1</h2>
        </div>
        <div class="reason-desc">
          <p>description</p>
        </div>
      </div>
    </div>
    <div id="q-2" class="question-group row">
      <div class="question-wrap">
        <p>question 2?</p>
        <label class="radio-inline">
                <input type="radio" name="q2" value="yes"> Yes
            </label>
        <label class="radio-inline">
                <input type="radio" name="q2" value="no"> No
            </label>
      </div>
      <div id="q2-yes" class="reason-wrap">
        <div class="reason">
          <h2><span class="number">2</span>reason 2</h2>
        </div>
        <div class="reason-desc">
          <p>description</p>
        </div>
      </div>
      <div id="q2-no" class="reason-wrap">
        <div class="reason">
          <h2><span class="number">2</span>reason 2</h2>
        </div>
        <div class="reason-desc">
          <p>description</p>
        </div>
      </div>
    </div>
    
    <div id="q-3" class="question-group row">
      <div class="question-wrap">
        <p>question 3?</p>
        <label class="radio-inline">
                <input type="radio" name="q3" value="yes"> Yes
            </label>
        <label class="radio-inline">
                <input type="radio" name="q3" value="no"> No
            </label>
      </div>
      <div id="q3-yes" class="reason-wrap">
        <div class="reason">
          <h2><span class="number">3</span>reason 3</h2>
        </div>
        <div class="reason-desc">
          <p>description</p>
        </div>
      </div>
      <div id="q3-no" class="reason-wrap">
        <div class="reason">
          <h2><span class="number">3</span>reason 3</h2>
        </div>
        <div class="reason-desc">
          <p>description</p>
        </div>
      </div>
    </div>
  </form>
  </div>

Additionally, please double-check and use <div id="q2-no"> instead of having duplicates with <div id="q2-yes">.

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

Monitoring the progress of file uploads within itemView

In the process of developing an application using Marionette/Backbone, I have successfully implemented file uploads over an AJAX call. Now, I am looking for a way to provide users with feedback on when they can select the uploaded file and proceed with mod ...

Issues with calculating SUM in MySQL within a Node.js Express application using EJS template

I am currently working on developing a dashboard for my Node.js project. The aim is to calculate the sum of certain values for an overview. While the SELECT statement works fine in my MySQL database, when I incorporate it into my Node project, I do not rec ...

What is the best way to reset Owl Carousel following an ajax request?

I am attempting to reinitialize the owl carousel following a successful ajax call. The ajax call will update the data while retaining the same view. I am encountering an issue where the carousel structure in the view does not reinitialize, and I am unsure ...

Using the methods res.render() and res.redirect() in Express.js

I'm facing a challenge with a route in my express app, where I need to achieve the following: Retrieve data from an external source (successful) Show an HTML page with socket.io listening for messages (successful) Conduct lengthy calculations Send a ...

Error: No @Directive annotation was found on the ChartComponent for Highcharts in Angular 2

I'm having trouble integrating Highcharts for Angular 2 into my project. After adding the CHART_DIRECTIVES to the directives array in @Component, I encountered the following error in my browser console: EXCEPTION: Error: Uncaught (in promise): No ...

Add a new component in front of another component based on its attribute value

Creating a dynamic DIV and positioning it in between other Div's based on their attribute value is the goal. The desired outcome is to maintain sequence. <div data-door="1">1</div> <div data-door="3">3</div> <div data-door ...

Select a dropdown menu option in Cypress by clicking on it only if it is checked

In this html code snippet, I have multiple elements within a dropdown menu. I am looking for a way to click on an item only if it is selected (has the class selected) or has a check mark in front of the name, as shown in this screenshot. How can I achieve ...

Canvg | Is there a way to customize canvas elements while converting from SVG?

Recently, I encountered an issue with styling SVG graphics dynamically generated from data. The SVG graphic appears like this: https://i.sstatic.net/xvIpE.png To address the problem, I turned to Canvg in hopes of converting the SVG into an image or PDF us ...

"Patience is key as we await the resolution of a promise within the confines of an emitter

My goal is to wait for the promise to be resolved before continuing when the someevent event is fired. However, even though I use a then in my code snippet below, it seems that the process shuts down before the slowFunctionThatReturnsPromise is resolved, ...

Enhancing UI Design with Styled-Components and Material Components using Media Queries

Struggling to grasp media queries with MUI and styled components. Take a look at the following syntax using styled-components: Syntax 1: const Video = styled.video` width: 860px; @media ${device.mobileSM} { width: 90%; } `; Additionally, there ...

How to manipulate local JSON files using AngularJS

I recently started learning angularjs and have been spending hours online trying to figure out how to access data from a local json file without the need for hosting it on localhost. Unfortunately, I haven't come across any solutions yet. I attempted ...

Steps to forward a restricted user to a specific webpage

I am currently utilizing NextJs and am in the process of creating a redirecting function for users who have been banned or blocked from accessing the DB/session. My attempt at this involved: redirect.js, where I created a custom redirect function. impo ...

Final div class nested within the HTML and styled with CSS

Is there a way to keep the last div (class) from sliding underneath? I applied margin-right to .artist_wrap. I assumed that using overflow: hidden would contain it within #music_videos_wrap, but it just disappears. Any assistance is greatly appreciated. H ...

Steps for displaying a loading image during the rendering of a drop-down list (but not during data loading):

Using jQuery's autocomplete combobox with a large dataset of around 1,000 items. The data loads smoothly from the server, but there is a delay when expanding the drop-down list to render on screen. Is there a way to capture the initial click event on ...

Establish the directive upon receiving the broadcast

Is there a way to trigger a directive when a specific event occurs on the backend and sets a value to false?... This is where the event is being captured .factory('AuthInterceptor', function($q, $injector, $rootScope) { return { ...

Unable to dial phone numbers when clicking 'Click to call' link on Android devices

Within my Cordova android application, I have a link set up like this: <a href = "tel:011123456789">Click to Call</a> While this click-to-call functionality works smoothly in IOS, it seems to be hindered in Android by an issue such as: 11- ...

I am interested in running JavaScript code on a page that has been loaded through AJAX

I am struggling to execute the Javascript loaded within an ajax page. Here is the link to my loaded ajax page: https://jsfiddle.net/4dsbry7j/ JS : var xmlhttp = new XMLHttpRequest(); var url = "http://localhost/ajax/find2.php"; xmlhttp.onreadystatechang ...

Having trouble changing the chosen selection in the material UI dropdown menu

I've encountered an issue with my material ui code for a select dropdown. It seems that the selected option is not updating properly within the dropdown. <FormControl variant="outlined" className={classes.formControl}> <InputLabel ref={ ...

Let's implement a sleek "load more" feature for your ASP.NET repeater just

Hey there, I was wondering if anyone has any cool samples of how to implement a Twitter-style load more items feature. How can I accomplish this using an ASP.NET repeater? ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...