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
Instead of this:
You can use
.triggerHandler(), like this:This executes the
clickhandler your just bound without actually executing aclickon the box, so it makes the initial state match, without interfering. Overall it looks like this:You can give it a try here