Richard77
Richard77

Reputation: 21631

JQuery: How to hide/display a div depending on the initial state of a checkbox?

Let's say I've this a checkbox and a div that contains elements that I want to hide/display depending on the checkbox being checked or not.

<input type = "checkbox" id = "myCheckbox"/>
<div id = "display-hide">
  //Contains more elements
</div>

Now, here is the JQuery script that does the trick.

<script type = "text/javascript">
  $(function () {
    $("#myCheckbox").click(function(){
        $("#display-hide").toggle(this.checked);
     });
      $("#display-hide").hide();
  });    
</script>

The first time I access the page, everything works fine (i.e. div is hidden - when I check the checkbox, the div is displayed).

BUT, when I come back to the page (to edit, for instance), no-matter the value of the checkbox (checked or not), the div is hidden first. The div becomes only visible after I uncheck then check again.

I guess that because of this statement:

$("#display-hide").hide();

Is there anyway to verify the value of the checkbox and hide/show the div accordingly?

Thanks for helping

Upvotes: 0

Views: 1426

Answers (2)

Nick Craver
Nick Craver

Reputation: 630429

Instead of this:

$("#display-hide").hide();

You can use .triggerHandler(), like this:

$("#myCheckbox").triggerHandler('click');

This executes the click handler your just bound without actually executing a click on the box, so it makes the initial state match, without interfering. Overall it looks like this:

$("#myCheckbox").click(function(){
  $("#display-hide").toggle(this.checked);
}).triggerHandler('click');

You can give it a try here

Upvotes: 6

Bang Dao
Bang Dao

Reputation: 5102

I think you should edit a little in your code

script type = "text/javascript">
  $(function () {
    $("#myCheckbox").click(function(){
        $("#display-hide").toggle(this.checked);
     });
     if($("#myCheckbox").attr("checked"))
     {
          $("#display-hide").show();
     }
     else
     {
          $("#display-hide").hide();
     }
  });    
</script>

Upvotes: 1

Related Questions