Reputation: 573
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>
Upvotes: 1
Views: 546
Reputation: 6646
You're mixing JavaScript and jQuery! As dcangulo stated, change the element you're sending to the function in the document ready part:
$(document).ready(function() {
hasPrereqBlockHandler($("#hasPrereqBlock").get(0));
});
get
returns the element at the given index, and since there is one (you're using an ID, so I assume there is just one) it sends the first. The element sent to the function is the same as the this
value that gets send when you check the input.
more information about the get function
Upvotes: 0
Reputation: 530
Your jQuery object has no .checked
. If you console.log
cb.checked
it returns undefined
instead of a boolean, so you know there is something wrong. .checked
doesn't exists on a jQuery checkbox object.
Change:
cb.checked
Into:
cb.prop('checked')
Upvotes: 2