jason
jason

Reputation: 4801

Running the same event handler for two different events on different elements

Say I have a form with a field and a submit button.

I want the same function to run when either action (click or change) occurs.

Currently I have it set up this way :

$("#btn-search").click(function() {
    $(".forminput").change();
});

$(".forminput").change(function() {
    //do stuff
});

However, this seems to fire the //do stuff part multiple times. Is there a better way to do it, or is the problem likely elsewhere?

Upvotes: 1

Views: 133

Answers (4)

Alex
Alex

Reputation: 2174

You can use one eventHandler for both cases. In case if you need to distinguish events you can use event argument to handle them differently

function eventHandler (event) {}

$("#btn-search").click(eventHandler);

$(".forminput").change(eventHandler);

Upvotes: 1

PeterKA
PeterKA

Reputation: 24638

The following should be a better approach and should prevent your code from firing multiple times.

function doStuff(e) { 
    e.stopImmediatePropagation();
    // do stuff
}
$('.forminput').on('change', doStuff);
$('#btn-search').on('click', doStuff);

Upvotes: 0

orhanhenrik
orhanhenrik

Reputation: 1415

You can make a function which will be called for the events you want. Example:

$('#one').click(foo);
$('#two').change(foo);

function foo(){
    // do stuff... this and $(this) are also usable.
}

Upvotes: 1

Scimonster
Scimonster

Reputation: 33399

If your event handler doesn't require being in the context of .forminput (i.e. it doesn't use $(this) at all), then you can create one function to use for both of them:

function clickChangeHandler(){
    // do stuff
}

$("#btn-search").click(clickChangeHandler);
$(".forminput").change(clickChangeHandler);

Upvotes: 1

Related Questions