no_leaf
no_leaf

Reputation: 43

Jquery Show/Hide div depending on multiple radio button group selection

I couldn't figure out how to show/hide div depending on multiple radio button selection. If both Question 1 and Question 2 selected as Yes, than div should be shown, in any other cases div should be hidden.

$(function() {
  $("input[name='q1']").click(function() {
    if ($('input[name=q1]:checked').val() == "Yes") {
      $("input[name='q2']").click(function() {
        if ($('input[name=q2]:checked').val() == "Yes") {
          $("#part2").show();
        } else {
          $("#part2").hide();
        }
      });
    } else {
      $("#part2").hide();
    }
  });
});
<input type="radio" class="hideshow" name="q1" value="Yes" /> Yes
<input type="radio" id="test" name="q1" value="No" /> No
<br />
<input type="radio" class="hideshow2" name="q2" value="Yes" /> Yes
<input type="radio" id="test2" name="q2" value="No" /> No
<br />
<div id="part2" style="display:none; margin-top:10px;">
  TEXT
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

DEMO

Upvotes: 0

Views: 54

Answers (1)

Sven Eberth
Sven Eberth

Reputation: 3116

Better use only one change handler and one if to check you condition.
The change event will also be fired, when a label is clicked, therefore it might be better than the click event.
And when you bind the click handler for q2 in the handler of q1, you bind it on every click on q1 again.

$(function() {
  $("input[name='q1'], input[name='q2']").change(function() {
    if ($('input[name=q1]:checked').val() === "Yes" && $('input[name=q2]:checked').val() === "Yes") {
      $("#part2").show();
    } else {
      $("#part2").hide();
    }
  });
});
<input type="radio" class="hideshow" name="q1" value="Yes" /> Yes
<input type="radio" id="test" name="q1" value="No" /> No
<br />
<input type="radio" class="hideshow2" name="q2" value="Yes" /> Yes
<input type="radio" id="test2" name="q2" value="No" /> No
<br />
<div id="part2" style="display:none; margin-top:10px;">
  TEXT
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 2

Related Questions