This question is related to:
Hide or show div based on checkBox status
How to check if the checkbox is already checked on load.
I am using asp-for to load the content.
CodePudding user response:
If you want to check if the checkbox is already checked on load.Try to use $(function(){})
:
html:
<input type="checkbox" asp-for="gridCheck1" />
<div id="ShowHideMe">
<p>some content</p>
</div>
js:
$(function () {
myFunction();
)};
$('#gridCheck1').change(function () {
myFunction();
});
function myFunction() {
const div = document.getElementById('ShowHideMe');
if ($("#gridCheck1").prop('checked')) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
CodePudding user response:
How i solved this, hope it helps :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script>
$(function() {
$('#gridCheck1').change(function() {
myFunction();
});
});
$(document).ready(function() {
myFunction();
});
function myFunction() {
$('#ShowHideMe').toggle($('#gridCheck1').is(':checked'));
}
</script>
<div >
<div >Checkbox</div>
<div >
<div >
<input type="checkbox" id="gridCheck1">
<label for="gridCheck1">
Example checkbox
</label>
</div>
</div>
</div>
<div id="ShowHideMe" style="display:none">
<p>some content</p>
</div>