Tim
Tim

Reputation: 19

Trigger function on page load (jQuery)

I have the following function, which runs on click:

$(document).ready(function() {

    $('p.distance-units label input:radio').click(function() {
        var units = $(this).parents('label').attr('units');


        if ($(this).parents('label').hasClass('unchecked')) {
            changeDistanceUnits(units);
        }


    });

I would like it to be triggered on page load as well.

Thanks, Tim

Upvotes: 1

Views: 326

Answers (4)

Balachandran
Balachandran

Reputation: 9637

  Use trigger to call initially 

 $('p.distance-units label input:radio').on("click",calBack);
     // Trigger
     $('p.distance-units label input:radio').trigger("click");

function calBack(){

            if ($(this).parents('label').hasClass('unchecked')) {
                changeDistanceUnits(units);
            }
    }

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You might want to trigger the click for only the checked items so

$(document).ready(function () {
    $('p.distance-units label input:radio').on('click',function () {
        var units = $(this).parents('label').attr('units');
        if ($(this).parents('label').hasClass('unchecked')) {
            changeDistanceUnits(units);
        }
    }).filter(':checked').triggerHandler('click');
});

Upvotes: 0

Ram
Ram

Reputation: 144659

Simply call the click method:

$('p.distance-units label input:radio').click(function() {
  // ...
}).click();

Upvotes: 1

Viscocent
Viscocent

Reputation: 2064

try this:

$(document).ready(function() {

    $('p.distance-units label input:radio').click(function() {
        var units = $(this).parents('label').attr('units');

        if ($(this).parents('label').hasClass('unchecked')) {
            changeDistanceUnits(units);
        }
    });

    $('p.distance-units label input:radio').click();
});

Upvotes: 0

Related Questions