6

I'm writing a form validation script and would like to validate a given field when its onblur event fires. I would also like to use event bubbling so i don't have to attach an onblur event to each individual form field. Unfortunately, the onblur event doesn't bubble. Just wondering if anyone knows of an elegant solution that can produce the same effect.

Stephen Sorensen
  • 11,455
  • 13
  • 33
  • 46
  • each form field is has a different validate function or it's the same for all fields? – Peter Oct 06 '09 at 13:54
  • they all use the same callback function. the callback function looks for certain classes on the html element that tell it how to validate ( like "required" or "integer" ) – Stephen Sorensen Oct 06 '09 at 14:02

4 Answers4

9

You're going to need to use event capturing (as opposed to bubbling) for standards-compliant browsers and focusout for IE:

if (myForm.addEventListener) {
    // Standards browsers can use event Capturing. NOTE: capturing 
    // is triggered by virtue of setting the last parameter to true
    myForm.addEventListener('blur', validationFunction, true);
}
else {
    // IE can use its proprietary focusout event, which 
    // bubbles in the way you wish blur to:
    myForm.onfocusout = validationFunction;
}

// And of course detect the element that blurred in your handler:
function validationFunction(e) {
    var target = e ? e.target : window.event.srcElement;

    // ...
}

See http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html for the juicy details

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
7

use 'Focusout' event as it has Bubble up effect..thanks.

Umesh K.
  • 311
  • 2
  • 6
  • 14
2

ppk has a technique for this, including the necessary workarounds for IE: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html

NickFitz
  • 34,537
  • 8
  • 43
  • 40
-2

aa, you can simply add the onblur event on the form, and will call the validation every time you change focus on any of the elements inside it

TheBrain
  • 5,528
  • 2
  • 25
  • 26
  • 1
    are you sure? I wouldn't have thought that the form would blur at all, especially since it can't have focus in the first place. – nickf Oct 06 '09 at 14:00