Skip to content Skip to sidebar Skip to footer

How To Hide And Show Item If Checkbox Is Checked

I am trying to hide and show an area based on whether a checkbox is checked. I've tried some options but either the area is visible all of the time or it is hidden all of the time.

Solution 1:

Try this code

     $(document).ready(function () {
     $('#chkbxMGift').click(function () {
         var $this = $(this);
         if ($this.is(':checked')) {
             $('#shcompany').hide();
         } else {
             $('#shcompany').show();
         }
     });
 });

Hope it solves your issue

Solution 2:

Your selector is wrong.

var mgift = $('#chkbxMGift input[type=checkbox]'); 

This means you select the childnode input from parent #chkbxMGift.

I believe this is the selector you need:

var mgift = $('input#chkbxMGift[type=checkbox]'); 

And here are some improvements on your code:

$(document).ready(function () {
    var mgift = $('input#chkbxMGift[type=checkbox]'); 
    var shcompany = $('#shcompany');
    // check for default status (when checked, show the shcompany)if (mgift.attr('checked') !== undefined){
        shcompany.show();
    } else {
        shcompany.hide();
    }

    // then simply toggle the shcompany on every change
    mgift.change(function(){
        shcompany.toggle();
    });
}); 

jQuery's toggle is really useful and added in version 1.0, so you should be able to just go with that.

Here's a proof of concept in a jsFiddle, with only the bare minimum:

http://jsfiddle.net/Y39Bu/1/

Solution 3:

This is stolen from this answer:

http://jsfiddle.net/MH8e4/4/

$('.wpbook_hidden').css({
'display': 'none'
});

alert($(':checkbox:checked').attr('id'))
$(':checkbox').change(function() {
    var option = 'wpbook_option_' + $(this).attr('id');
    if ($('.' + option).css('display') == 'none') {
        $('.' + option).fadeIn();
    }
    else {
        $('.' + option).fadeOut();
    }
});

search for similar questions before you ask yours. Please give the original author the credit if this solves your problem

Solution 4:

Have you tried changing the CSS directly? Such as

document.getElementById("shcompany").style.display="none";

or

document.getElementById("shcompany").style.visibility="hidden";

(or "visible")

Solution 5:

Why use JQuery when a simple CSS property change can do the trick?

Just change the div's class or modify it's style:

If you want it to take up space even when hidden use visibility:hidden (respectively visibility:visible)

if you want it NOT to take space when hidden use css display:none (respectively display:block)

Post a Comment for "How To Hide And Show Item If Checkbox Is Checked"