I have a checkbox. I have a div with content under the checkbox. When the checkbox is checked, the div is hidden. When the checkbox is unchecked, the div is visible.
When the page is loaded, I want the checkbox to be checked and the div to already be hidden. When the checkbox is unchecked, the div should be visible.
I have tried using the click function, and I've tried using show and hide. But I can't get the code to do what I want. Any help is greatly appreciated.
Here's my code:
<script>
$(document).ready(function()
{
$('#checkbox_content').change(function()
{
if(this.checked)
$('#content').fadeOut('slow');
else
$('#content').fadeIn('slow');
});
});
</script>
<div>
<form action="">
<input type="checkbox" name="" value="" id="checkbox_content" checked="checked">
</form>
</div>
<div id="content">
div content here
</div>
Just add display:none
to your div:
<div id="content" style="display:none;">
div content here
</div>
The div will now be hidden by default, the rest of your code will do what you want without any change.
Here is the fiddle to your query.
https://jsfiddle.net/swaprks/L8eyrmjs/
JAVASCRIPT:
$(document).ready(function()
{
$('#checkbox_content').change(function()
{
if(this.checked)
$('#content').fadeOut('slow');
else
$('#content').fadeIn('slow');
});
});
HTML:
<div>
<form action="">
<input type="checkbox" name="" value="" id="checkbox_content" checked="checked">
</form>
</div>
<div id="content" class="displayNone">
div content here
</div>
CSS:
.displayNone{display:none;}
Hope this helps. Basically you just need to hide the div at the start as you are making the checkbox as checked using the property "checked". Tip: It is better to maintain CSS in a separate css file rather than writing it inline.
You can also do like this,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <form action=""> <input type="checkbox" name="" value="" id="checkbox_content" checked="checked" onChange="$('#content').fadeToggle('slow');"> </form> <div id="content" style="display:none"> div content here </div>
It seems you are using jQuery.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.