Search code examples
javascripthtmlshow-hide

hiding div based on unchecking checkboxes


I have multiple checkboxes in a form. Based on clicking those checkboxes, I show a div section. But if I uncheck even one checkbox, that div section gets hidden. How do I make sure that div section is hidden only if all checkboxes are unchecked. Crude way can be to write my own 'display' method which will check if all checkboxes are unchecked and then hide the div section. Any easier solution??


Solution

  • The following code will show the div if one or more checkboxes has been checked:

    jQuery

    Version 1:

    $("input[name='mycheckboxes']").change(function() {
      $("#showme").toggle($("input[name='mycheckboxes']:checked").length>0);
    });
    

    Version 2 (more efficient):

    var MyCheckboxes=$("input[name='mycheckboxes']");
    
    MyCheckboxes.change(function() {
      $("#showme").toggle(MyCheckboxes.is(":checked"));
    });
    

    HTML

    <input type="checkbox" name="mycheckboxes" />
    <input type="checkbox" name="mycheckboxes" />
    <input type="checkbox" name="mycheckboxes" />
    <input type="checkbox" name="mycheckboxes" />
    
    <div id="showme" style="display: none">Show me</div>
    

    Code in action (Version 1).

    Code in action (Version 2).

    --- Different Checkbox Names Version ---

    For different named checkboxes, wrap them in a DIV with an identifier. E.g.

    jQuery

    var MyCheckboxes=$("#checkboxgroup :checkbox");
    
    MyCheckboxes.change(function() {
      $("#showme").toggle(MyCheckboxes.is(":checked"));
    });
    

    HTML

    <div id="checkboxgroup">
      <input type="checkbox" name="mycheckbox1" />
      <input type="checkbox" name="mycheckbox2" />
      <input type="checkbox" name="mycheckbox3" />
      <input type="checkbox" name="mycheckbox4" />
    </div>
    
    <div id="showme" style="display: none">Show me</div>
    

    This code in action.