views:

193

answers:

3

Is there a way to have keyup, keypress, blur, and change events call the same function in one line or do I have to do them separately?

The problem I have is that I need to validate some data with a db lookup and would like to make sure that there is no way that the validation is missed weather it is typed or pasted into the box.

+1  A: 

You can use bind method to attach function to several events. Just pass the event names and the handler function as in this code:

$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

Another option is to use chaining support of jquery api.

Giorgi
+4  A: 

You can use bind to bind a function to multiple events:

$('#element').bind('keyup keypress blur change', function() {
    ...
});

Or just pass the function as the parameter to normal event functions:

$('#element')
    .keyup(myFunction)
    .keypress(myFunction)
    .blur(myFunction)
    .change(myFunction)

var myFunction = function() {
   ...
}
Tatu Ulmanen
Worked Great, thanks
dweebsonduty
A: 

If you attach the same event handler to several events, you often run into the issue of more than one of them firing at once (e.g. user presses tab after editing; keydown, change, and blur might all fire).

It sounds like what you actually want is something like this:

$('#ValidatedInput').keydown(function(evt) {
  // If enter is pressed
  if (evt.keyCode === 13) {
    evt.preventDefault();

    // If changes have been made to the input's value, 
    //  blur() will result in a change event being fired.
    this.blur();
  }
});

$('#ValidatedInput').change(function(evt) {
  var valueToValidate = this.value;

  // Your validation callback/logic here.
});
Dave Ward