Reputation: 21631
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
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');
Upvotes: 6
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