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?
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.
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.
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.
You can use the jQuery on method.
$("#inpt").on( "change keypress", function () {
code
});
You can save the function and bind it to both:
var fn = function(){ /*some code*/ };
$("#inpt").change(fn).keypress(fn);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With