MrOrange MrOrange - 1 month ago 14
jQuery Question

Calling jQuery function once on page load

I have defined a jQuery function, which runs when the input is changed (showing/hiding certain divs). So far so good.

My question: how do I call this function once when the page loads?

With my lack of experience I am just making it worse while trying the answers I found so far (dragging the functions outside the document ready declaration, etc.). I guess the functions have to stay where they are, but calling them doesn't seem to work yet. The script:

jQuery(document).ready(function($) {

$('input[name=project-type]').change(chooseProject);

function chooseProject() {
var val = $(this).val();
$('#div1').hide();
$('#div2').hide();
$('#div3').hide();
if (val == 'Short') {
$('#div1').show();
}
else if (val == 'Long') {
$('#div1').show();
$('#div3').show();
}
}

});


Some background: the input is a radio button, and through a multi-step contact form the selected option is remembered on a new pageload, however without the change event the function is not kicking in.

After hours of struggling help is really appreciated!

Answer

You can trigger the change event on that element after you have bound it. This executes the handler as if it were triggered naturally by the user.

I would try something like this:

jQuery(document).ready(function($) {
    //function declaration
    $('input[name=project-type]').on('change', chooseProject);
    $('input[name=project-type]').trigger('change');
});