Search code examples
javascriptjqueryhideshow

how to toggle text when checkbox(es) are checked and hide when nothing is checked


When checking a checkbox, the text Checked is shown. When unchecking all the checkboxes, how can I hide the text Checked?

$('.rafcheckbox').click(function() {
  $(".rafoptions").show();
});
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="rafoptions" style="display:none">Checked</div>


Solution

  • To make this work you can use the :checked selector and the length property to determine if any of the boxes are checked. Then you can use toggle() to hide/show the div as required.

    var $checkboxes = $('.rafcheckbox').change(function() {
      var anyChecked = $checkboxes.filter(':checked').length != 0;
      $(".rafoptions").toggle(anyChecked);
    });
    .rafoptions { display: none; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" class="rafcheckbox" value="1" />
    <input type="checkbox" class="rafcheckbox" value="2" />
    <input type="checkbox" class="rafcheckbox" value="3" />
    <div class="rafoptions">Checked</div>