David542
David542

Reputation: 110093

Trigger jQuery event on three separate events

I have the following function:

function update_missing_info() {
    // do something
}

I want to trigger this function (1) when a particular page loads, (2) when one dropdown is changed, and (3) when another dropdown changes.

Here is how it would look long-form:

// on page load
if ($('.billing-page').length > 0) {
    update_missing_info();
};

// on changing first dropdown
$('select[name="hd"]').change(function() {
    update_missing_info();
});

// on changing second dropdown
$('select[name="length"]').change(function() {
    update_missing_info();
});

Is there a way to combine all three of these together, so I can do something like:

if (any of the three conditions met) {
    update_missing_info();
}

Upvotes: 0

Views: 33

Answers (2)

lonewolf217
lonewolf217

Reputation: 629

you can combine the two change events into this, but i dont know if you can combine all three

$("select[name='hd'],select[name='length']").change(function() {
   update_missing_info();
});

Upvotes: 0

Aleks G
Aleks G

Reputation: 57306

You can certainly combine the events by specifying multiple selectors in jQuery. You cannot combine this withe the first one, as it's not an event trigger but rather a simply conditional call. The simplest you can get this to would be:

// on page load
if ($('.billing-page').length > 0) {
    update_missing_info();
};

// on changing dropdowns
$('select[name="hd"], select[name="length"]').on('change', update_missing_info);

Note that you do not need an anonymous function in the event handler as you don't do anything in it accept calling another function without any parameters, therefore you can just specify that function as the event trigger.

Upvotes: 1

Related Questions