1

I want to display/hide a div based on whether a certain checkbox is checked or unchecked.

Please note this is not about using jQuery .click or .change function. These don't work in my case.

What I am trying to do is that a certain div to display if a checkbox field has a value checked="checked", otherwise hide it.

I don't want to show/hide anything by default. I want to hide only if checkbox is unchecked and if it's checked, the div should always show (even on page load).

here is the link to Fiddle (.click approach and it does not work for me) https://jsfiddle.net/a5s5s4k3/

You may notice that First Name checkbox is already checked but its adjacent div is still hidden.

Any help would be highly appreciated.

thanks

bakar
  • 129
  • 1
  • 2
  • 11

3 Answers3

2

You can do this with pure CSS if you're willing to change your markup a bit.

HTML

<p>
  <input type="checkbox" id="" name="" checked="checked" />
  <label>Enable First Name Field</label>
  <input type="text" id="" class="" name="" value="" />
</p>

<p>
  <input class="check2" type="checkbox" id="" name="" />
  <label>Enable Last Name Field</label>
  <input type="text" id="" name="" value="" />
</p>

CSS

input[type=checkbox] + label + input {
  display: none;
}

input[type=checkbox]:checked + label + input {
  display: block;
}

The + operator selects elements next to each other. In this case we're targeting the input next to the label next to the checkbox. Check out the MDN reference for sibling selectors if you aren't familiar with them. They're pretty handy.

Updated fiddle: https://jsfiddle.net/a5s5s4k3/2/

Sabrina
  • 617
  • 4
  • 14
  • It also has the bonus of working even if the user has javascript disabled. Something to keep in mind. – Sabrina Feb 27 '16 at 20:52
2

Write a function which will always check the status of the checkboxes and hide and show the inputs accordingly. And you can call this function on document ready and then on change of the checkboxes. Refer the below code

 $(function(){
      formatUI();

    $('input[type="checkbox"]').on('change',function(){
       formatUI();
    });

    function formatUI()
    {
        $.each($('input[type="checkbox"]'),function(){
             if($(this).attr('checked') === 'checked')
             {
               $(this).parent().next('p').show();
             }
             else{
              $(this).parent().next('p').hide();
             }
        });
    }


   });

Here is a Wroking Fiddle

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
1

    $(document).on("click", "[type='checkbox']", function(e) {
            if (this.checked) {
                $(this).attr("value", "true");
            } else {
                $(this).attr("value","false");}
        });
<input type="checkbox" name="myCheckbox" checked="checked" value="true" />