tags:

views:

73

answers:

2

Hello,

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

+1  A: 

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>
Bang Dao
+4  A: 

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

Nick Craver
i like it more than .is(":checked")
KoolKabin
@Nick Craver: Well, this Javascript businness is usually hard to master. I need more focus on that. It working perfectly now. Thanks very much.
Richard77
@Richard - Welcome :) And btw you're doing much better even in the short example than a *lot* of developers, e.g. you're using a DOM property, `this.checked` where it's available. This is *absolutely* the right thing to do, no need to go through 10 methods to get a property that's right there, that alone many people can't get through their heads...you're already doing it correctly :)
Nick Craver
@Nick Craver: Well, wait and see how I can be dumb when it comes to Javascript (lol!).
Richard77
Thanks for the link
Richard77