I am facing a challenge with a set of div
s 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