Ivan
Ivan

Reputation: 15912

Chain two jquery events

If I have an event handler like:

function A() {
 ...
}

it's possible to assign to more than one event:

$("#test1").keyup(A);
$("#test2").change(A);

But I'm wondering if it's possible to do it with only one sentence, something like:

$("#test1").keyup, $("#test2").change (function () {
  ...
});

Upvotes: 6

Views: 3069

Answers (4)

karim79
karim79

Reputation: 342635

Yes, yes it is. It is really horrible though.

$("#test1").keyup(A).parent().find("#test2").change(A);

http://jsfiddle.net/8RwZY/

There is also this atrocity:

$("#test1, #test2").eq(0).keyup(A).end().eq(1).change(A);

http://jsfiddle.net/8RwZY/1/

Upvotes: 3

Jacek Kaniuk
Jacek Kaniuk

Reputation: 5229

$("#test2").bind('keyup change', A);

/edit as for different elements and events - it's:

$("#test1, #test2").bind('keyup change', A);

or

$("#test1").bind('keyup', A);
$("#test2").bind('change', A);

depending on what do You expect. There is no simpler way

Upvotes: 5

Jamiec
Jamiec

Reputation: 136074

If these were the same element, say #test1, then you can chain the methods

$('#test1').change(A).keyup(A);

However, with more than 1 element you can't chain them, or do anything else similar to your example.

Upvotes: 0

Luke Stevenson
Luke Stevenson

Reputation: 10341

Short answer? No. Long answer? Not at all.

Sorry not to have the answer you were hoping for. But the good news is that your code looks spot-on aside from that limitation.

Upvotes: -1

Related Questions