I'm using slideToggle
to display image related forms when a checkbox is enabled and hide it if not checked.
My menu structure is as follows:
<ul>
<li class="menu-item">
<p>
<label><input type="checkbox">...</input>Upload Image?</label>
</p>
<div class="settings-image">...image related forms...</div>
</li>
<li></li>
</ul>
My jQuery code:
jQuery(document).ready(function($) {
$('input[type="checkbox"]').change(function(){
$(this).toggleClass("option-checked", this.checked);
$(this).closest('li.menu-item').find('.settings-image').slideToggle();
});
});
This works just fine when the checkbox isn't checked
yet on pageload.
The problem is when the checkbox is checked
on pageload. Neither the toggleClass
name and settings-image
div shows by default.
Any help in the right direction is much appreciated.
You can put .trigger('change');
in your change function which will trigger the change when loaded.
$(document).ready(function($) {
$('input[type="checkbox"]').change(function() {
$(this).toggleClass("option-checked", this.checked);
$(this).closest('li.menu-item').find('.settings-image').slideToggle();
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="menu-item">
<p>
<label><input type="checkbox" checked>...</input>Upload Image?</label>
</p>
<div class="settings-image">...image related forms...</div>
</li>
<li></li>
</ul>