Search code examples
javascripthtmlvalidationfbjs

validation in javascript - remove the error msg on focus


i'm not very well-versed with javascript, so please bear with me.

i've a form in which i validate the controls with javascript. the error is displayed when the fields are empty via a div, but when i focus and type something in the textbox, the div should go away. but the error div doesn't and even if i type something valid, it still displays the div.

i'd like to know where am i going wrong with this script:

<script type="text/javascript">
var err = document.getElementById("errmsg");

function checkInput(inPut) {

    if (inPut.getValue() == "") {
            err.setStyle('display', 'block');
            err.setTextValue("Field cannot be empty!");
            inPut.focus();
            return false;
    }
    else {
            return true;
    }

}


function checkTextBox(textBox)
{

    if (textBox.getValue() == "") {
          err.setStyle('display', 'block');
          err.setTextValue("Field cannot be empty!");
          textBox.focus();
         return false;
    }     
    else if (!checkValidity(textBox.getValue())) {
                 err.setStyle('display', 'block');
         err.setTextValue("Please enter a valid email address!");
         textBox.focus();
         return false;
    }
    else {
         return true;
    }
}

. . . 
<div id="errmsg" class="invalid" style="display:none;"></div> <br />

. . . 
<input type="text" tabindex="1" name="name" id="name" class="input_contact" onblur="checkInput(this);"/>  <br />

. . . 
<input type="text" tabindex="2" name="email" id="email" class="input_contact" onblur="checkTextBox(this);"/>  <br />

it's a form in facebook app but while the fbjs works, i assume there's a problem with my basic javascript.


Solution

  • try this

    var err = document.getElementById("errmsg");
    
    function checkInput(inPut) {
    
        if (inPut.getValue() == "") {
                err.setStyle('display', 'block');
                err.setTextValue("Field cannot be empty!");
                inPut.focus();
                return false;
        }
        else {
                err.setStyle('display', 'none');
                err.setTextValue("");
                return true;
        }
    
    }
    
    
    function checkTextBox(textBox)
    {
    
        if (textBox.getValue() == "") {
              err.setStyle('display', 'block');
              err.setTextValue("Field cannot be empty!");
              textBox.focus();
             return false;
        }     
        else if (!checkValidity(textBox.getValue())) {
             err.setStyle('display', 'block');
             err.setTextValue("Please enter a valid email address!");
             textBox.focus();
             return false;
        }
        else {
             err.setStyle('display', 'none');
             err.setTextValue("");
             return true;
        }
    }