John Higgins John Higgins - 3 months ago 18
Javascript Question

run javascript on page load to hide form

I am using the following javascript to hide a form if the user clicks on a checkbox.

I am trying to get the code to run on page load but am not able to work out how to do this. Can anyone help?

$('#no_cage').change(function(){
if (this.checked) {
$('#cage_details').fadeOut();
} else {
$('#cage_details').fadeIn();
}
});


HTML:

<input name="no_cage" id="no_cage" type="checkbox" value="1" <?php echo $checked; ?>><label for="no_cage">Check if not required</label>

<div id="cage_details">

<form>

...

</form>

</div>


This works fine when a user clicks on the checkbox. But does not when it pulls from the DB and the checkbox is already selected on page load.

Answer

Just add this code inside the document ready handler. It will trigger the change event handler without it needing to actually change...

$('#no_cage').trigger("change");

Alternatively, just trigger the event where you declare it...

$('#no_cage').change(function(){
    if (this.checked) {
        $('#cage_details').fadeOut();
    }
    else {
        $('#cage_details').fadeIn();
    }                   
}).trigger("change");

That will add the event handler and then immediately execute it, in order to set the form to the correct state when the document has loaded.