devinfd
devinfd

Reputation: 79

jQuery :: How to execute one function based off two possible events

I'm looking for a clean way to fire one function that may be triggered by two possible events. For example:

$('form').on('submit', function() {
    stuff in here...
});

$('input').on('change', function() {
    same stuff in here as before...
});

I could do

function doStuff() {
    Stuff in here....
}

$('form').on('submit', function() {
    doStuff();
});

$('input').on('change', function() {
    doStuff();
});

But I was wondering if there was a more elegant way of doing this?

Upvotes: 1

Views: 70

Answers (2)

penacho123
penacho123

Reputation: 21

$(function() {

    $('form').submit(function(event) {
        event.preventDefault();
        stuff('aaa');
        $(this).unbind().submit();
    });

    $('input').change(function() {
        stuff('aaa');
    });
});

function stuff(param){
    // Some Processing!
    return(param);
}

Upvotes: 0

antoyo
antoyo

Reputation: 11913

function doStuff() {
    Stuff in here....
}

$('form').on('submit', doStuff);

$('input').on('change', doStuff);

Upvotes: 4

Related Questions