Reputation: 65
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>
Upvotes: 1
Views: 399
Reputation: 34914
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.
Upvotes: 0
Reputation: 1653
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.
Upvotes: 0