Search code examples
javascriptjqueryhtmlhideshow

Show/Hide divs based on radio button selection


I've gotten as far as showing a certain div based on the selection of "150" and "3m" but I can't get the div to hide if both of those aren't selected?

Code below:

$(document).ready(function() {
  $('input[value="100"], input[value="3m"]').change(function() {
    if ($('input[value="100"]').is(':checked') && $('input[value="3m"]').is(':checked')) {
      $('div').show();
    } else {
      $('div').hide();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>100</label>
<input class="amount" type="radio" name="amount" value="100" />
<label>150</label>
<input class="amount" type="radio" name="amount" value="150" />

<br>
<br>

<label>3</label>
<input class="month" type="radio" name="month" value="3m" />
<label>6</label>
<input class="month" type="radio" name="month" value="6m" />

<div style="display: none;">
  <div class="interest">
    £40
  </div>
  <div class="total-payable">
    £140
  </div>
  <div class="monthly-payment">
    £46.67
  </div>
  <div class="weekly-payment">
    £10.77
  </div>
</div>


Solution

  • Currently you're only updating the visibility of the div elements when the 100 or 3m radio button is changed - you want to update the visibility of the div elements on any radio button change by changing your selector:

    $('input[value="100"], input[value="3m"]')
    

    to

    $('input')
    

    $(document).ready(function() {
      $('input').change(function() {
        if ($('input[value="100"]').is(':checked') && $('input[value="3m"]').is(':checked')) {
          $('div').show();
        }
        else {
          $('div').hide();
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label>100</label>
    <input class="amount" type="radio" name="amount" value="100" />
    <label>150</label>
    <input class="amount" type="radio" name="amount" value="150" />
    
    <br><br>
    
    <label>3</label>
    <input class="month" type="radio" name="month" value="3m" />
    <label>6</label>
    <input class="month" type="radio" name="month" value="6m" />
    
    <div style="display: none;">
    <div class="interest">
    £40
    </div>
    <div class="total-payable">
    £140
    </div>
    <div class="monthly-payment">
    £46.67
    </div>
    <div class="weekly-payment">
    £10.77
    </div>
    </div>