Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle div visibility based on multiple checkboxes

Tags:

jquery

I have a multiple checkboxes. Checking any of them will make a div visible. Leaving them unchecked will hide the div. It almost works, thanks to Nick (http://stackoverflow.com/questions/4337378/toggle-div-based-on-checkbox-value) except that I want multiple checkboxes to toggle the div.

HTML:

<div id="somediv">
<input type="checkbox" class="form-checkbox" value="a" name="a">
<input type="checkbox" class="form-checkbox" value="b" name="b">
<input type="checkbox" class="form-checkbox" value="c" name="c">
<input type="checkbox" class="form-checkbox" value="d" name="d">
</div>

<div id="tog">tog content</div>

jQuery:

        var tog = $("#tog").hide();
        $('#somediv .form-checkbox').change(function() {              
          if ($(tog).css('display') == 'none') {
            tog.show();
          }       
        });

Another one:

        var tog = $("#tog").hide();
        $('#somediv .form-checkbox').change(function () {                
            $(tog).toggle(this.checked);
        }).change();

What am I missing? The issue is when unchecking one of them (not all) hides the div. The requirement is only if none is checked, then hide. And hidden by default. If any is checked, so keep it visible, no toggles.

Any hint would be very much appreciated. Thanks

like image 982
swan Avatar asked May 08 '26 15:05

swan


1 Answers

Try -

var tog = $("#tog").hide();
 $('#somediv .form-checkbox').change(function () {                
   $(tog).toggle($('.form-checkbox:checked').length > 0);
 }).change();

Demo - http://jsfiddle.net/VA4NP/

This is very similar to your second code sample. It uses $('.form-checkbox:checked').length > 0 as the argument passed to the toggle function, which should return true if any of the checkboxes are checked.

like image 189
ipr101 Avatar answered May 11 '26 05:05

ipr101



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!