jyotishka bora
jyotishka bora

Reputation: 3973

attaching same event handling code to multiple events in jquery

i have an input element, and i want bind both change and keypress event with the input, but event handling code is same for both the events. is there any short way of doing this instead of writing the same code twice. well, i could write a method, but wanted to see if there is any easier way of doing this

$("#inpt").change(function(){
   some code
});

$("#inpt").keypress(function(){
   same code
});

is there any way i can bind both events?

Upvotes: 16

Views: 7977

Answers (3)

Denis Ali
Denis Ali

Reputation: 1062

You can also use the 'live' event instead of the 'bind' one sugested. The 'live' event will cover even dynamic created elements. (Deprecated on 1.7)

Kaless1n and Matthew, to bind to multiple elements use the "Attribute Starts With Selector":

var fn = function() { /*some code*/ };

$('input[id^="foo_"]').click(fn).keyup(fn).keydown(fn);

That will bind to all 'input' elements where the 'id' starts with 'foo_'. You can change 'input' to any onther element and/or the 'id' with the 'name' attribute for example.

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532465

You can use the jQuery on method.

$("#inpt").on( "change keypress", function () {
     code
});

Upvotes: 39

sunsean
sunsean

Reputation: 2828

You can save the function and bind it to both:

var fn = function(){ /*some code*/ };
$("#inpt").change(fn).keypress(fn);

Upvotes: 6

Related Questions