Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery combine event functions

Tags:

instead of example:

$(".myfield").blur(function() {
    // validate
})
$(".myfield").keyup(function() {
    // validate
})

is there a way to combine these two?

like image 256
FFish Avatar asked Jul 19 '10 07:07

FFish


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.

Which event will help to perform two operations together in jQuery?

To achieve this you will have to bind a jQuery click event with the <div> element and then define an action against the click event.

Can multiple event handlers be added to a single element?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

What does .on do in jQuery?

The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree.


2 Answers

Yes

$(".myfield").bind('blur keyup', function(){
  // validate
});

Reference: .bind()

like image 161
jAndy Avatar answered Oct 04 '22 02:10

jAndy


In case you want to validate each for itself...

$('.myfield').live('blur keyup', function(event) {
  if (event.type == 'blur') {
    // validate on blur
  }
  if (event.type == 'keyup') {
    // validate on keyup
  }
});
like image 38
gearsdigital Avatar answered Oct 04 '22 00:10

gearsdigital