henrywright
henrywright

Reputation: 10240

How to detect if a button has been clicked OR an input's value has changed using jQuery?

My aim is to do something if an input's value changes OR a button is clicked.

I know how to implement these separately. For example:

$( 'form :input' ).change( function() {
    // Do something.
});

$( 'button' ).click( function() {
    // Do something.
});

But how can I implement them together? Here is some pseudo code example of what I'm trying to achieve:

if ( button is clicked ) OR ( input value changed ) {
    // Do something.
}

Upvotes: 1

Views: 273

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93611

Delegated events will allow combining both selectors and events:

$(document).on('change click', 'form :input, button', function() {
    // Do something.
    alert("event from " + this.outerHTML);
});

This will however trigger twice for a checkbox (change and click).

JSFiddle: http://jsfiddle.net/TrueBlueAussie/zqvs0ne9/1/

Upvotes: 0

MightyMouse
MightyMouse

Reputation: 13858

How about defining a function and just calling the same function in every case?

Something like this:

function f () {
    // do your stuff
}

$('form:input').change(f);
$('button').click(f);

Upvotes: 0

Alex Skakun
Alex Skakun

Reputation: 323

You can pass the same function as a handler.

function clickOrChangeHandler () {
    // do something
}

$('form:input').change(clickOrChangeHandler);

$('button').click(clickOrChangeHandler);

Upvotes: 2

Related Questions