views:

918

answers:

3

hi, 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?

+3  A: 

You can save the function and bind it to both:

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

You can use the jQuery bind method.

$("#inpt").bind( "change keypress", function () {
     code
});
tvanfosson
thank you, thats what i was looking for.
jyotishka bora
A: 

What if I want to have an argument to the function fn ?

Johanna