onChange and onBlur events

Discussion in 'Javascript' started by Christoph, Oct 19, 2004.

  1. Christoph

    Christoph Guest

    I'm trying to validate some HTML form elements when the
    user tabs out of each element. However, I'm having some
    It appears that the order of events is onChange followed
    some time afterwards by onBlur. I believe this to be the
    case because in my onChange script, if the validation fails,
    I force focus back to the field element. However, the focus
    still falls to the next field and not back to the field I tried to
    force the focus to. So it seems to me that the browser is
    actually tabbing out of the field only after the onChange
    script runs.
    Now, I can't just use onBlur because a part of my validation
    is checking to make sure the field is not blank. So using
    onBlur, when I tab out of a blank (or erroneous) field, it
    creates an endless loop where to adjacent fields are triggering
    their validation script when focus gets placed back to the
    erroneous field.
    So that brings me back to the onChange. Does anyone
    know how I can keep focus on the erroneous field after
    the onChange script fires? Because simply forcing focus
    on the field doesn't seem to be working.

    Thank you for your time and consideration.

    Christoph, Oct 19, 2004
    1. Advertisements

  2. Christoph

    Lee Guest

    Christoph said:
    In general, I don't like it when the script moves my focus.
    It's annoying and it's not going to guarantee correct input,
    anyway, because if I type the same bad value twice, it has
    not changed, so the onChange handler won't fire. That's not
    enough reason to use onBlur, though because even if you work
    around the looping problem, there are still too many things
    that can cause a field to lose focus before the user is ready
    to have the input validated. What it does mean is that you
    should also validate onSubmit and, as always, on the server.

    The following inserts a 1/10 second delay before setting the
    focus back to the field that failed validation:

    <script type="text/javascript">
    var globalTakeFocus=null;

    function setFocus(ref) {

    function validateField(ref) {
    if (ref.value != "ok") {
    alert("Value must be \"ok\"");
    <input onchange="validateField(this)"><br>
    <input onchange="validateField(this)"><br>
    <input onchange="validateField(this)">
    Lee, Oct 19, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.