I have a checkbox on my html view which looks like that:
<input type="checkbox" id="hasPrereqBlock" name="hasPrereqBlock" onchange="hasPrereqBlockHandler(this)">
And the function that gets triggered by that, looks like that:
function hasPrereqBlockHandler(cb){
if (cb.checked){
$("#campaignPrereqBlockRevDiv").show();
$("#instruction_1_RevDiv_M").hide();
$("#instruction_2_RevDiv").show();
} else {
$("#campaignPrereqBlockRevDiv").hide();
$("#instruction_1_RevDiv_M").show();
$("#instruction_2_RevDiv").hide();
}
}
When i load the page i want to execute this function and give it a reference to the checkbox, so it displays only the wanted stuff, due to the status of the checkbox, so i have this function:
$(document).ready(function() {
hasPrereqBlockHandler($("#hasPrereqBlock"));
});
I also tried it with document.getElementById("hasPrereqBlock") instead of $("#hasPrereqBlock"), but every of thos 3 elements are shown and they are only hidden when i click the checkbox. Why does my code not work?
function hasPrereqBlockHandler(cb) {
if (cb.checked) {
$("#campaignPrereqBlockRevDiv").show();
$("#instruction_1_RevDiv_M").hide();
$("#instruction_2_RevDiv").show();
} else {
$("#campaignPrereqBlockRevDiv").hide();
$("#instruction_1_RevDiv_M").show();
$("#instruction_2_RevDiv").hide();
}
}
$(document).ready(function() {
console.log("document ready");
hasPrereqBlockHandler($("#hasPrereqBlock"));
});
#campaignPrereqBlockRevDiv,
#instruction_2_RevDiv {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="hasPrereqBlock" name="hasPrereqBlock" onchange="hasPrereqBlockHandler(this)">
<div id="instruction_1_RevDiv_M">Review 1</div>
<br>
<div id="instruction_2_RevDiv">Review 2</div>
<br>
<div id="campaignPrereqBlockRevDiv">Campaing</div>
Your jQuery object has no
.checked. If youconsole.logcb.checkedit returnsundefinedinstead of a boolean, so you know there is something wrong..checkeddoesn't exists on a jQuery checkbox object.Change:
Into: