I am currently using
$("#some-box").click(function(){
$("#main-box").toggle();
});
Which works well, except for when the checkbox is part of a page that saves the checkboxes status. If a checkbox is saved as ticked, the main-box (which is revealed when the checkbox is clicked) is hidden on reload, and is only visible if the checkbox is clicked, which in now would mean "unticked" checkbox (as expected with the toggle).
How can I check on page load if the checkbox is already ticked, in which case to trigger the toggle automatically?
We can check the status of a checkbox by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') .
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
JS code: // Checkbox checked and input disbaled when page loads $('#checkbox'). prop('checked', true); if ($('#checkbox').is(':checked') == true) { $('#textInput').
this should work:
if ($("#some-box").is(':checked')){
$("#main-box").show();
}
.toggle()
accepts the state - so you could pass whether to show or hide an element on a particular call:
$("#some-box").change(function(){
$("#main-box").toggle($(this).is(':checked'));
});
$('#some-box').trigger('change');
PS: as you can see I'm proposing to use change
event instead of click
Online demo: http://jsfiddle.net/R4Bjw/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With