Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 776
jyotishka bora Avatar asked Feb 04 '09 03:02

jyotishka bora


People also ask

Can we use two events together in jQuery?

The jQuery . on() can attach multiple events on an element. In the below code I have attached 2 events to the p element. So when the element is clicked or mouse leaves this element, you will get alert box displayed.

Can we have more than one event handler method for same event?

One event can have more than one event handler method in the same class or in different classes. At the run time only one handler method will be triggered at a time. After triggering the one that has to be deactivated and then another handler method will have to be registered to be triggered.

How does jQuery handle multiple click events?

Set button attribute disable using jQuery after first click in callback function. This will help avoiding multiple clicking. To avoid multiple click events on an element, you can disable the element when it is clicked for the first time.


3 Answers

You can use the jQuery on method.

$("#inpt").on( "change keypress", function () {
     code
});
like image 162
tvanfosson Avatar answered Oct 08 '22 14:10

tvanfosson


You can save the function and bind it to both:

var fn = function(){ /*some code*/ };
$("#inpt").change(fn).keypress(fn);
like image 42
sunsean Avatar answered Oct 08 '22 13:10

sunsean


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.

like image 1
Denis Ali Avatar answered Oct 08 '22 14:10

Denis Ali