2

So I have this form:

<form name="login" id="login" action="" method="POST" onSubmit="return test()">
        <input type="text" size="10" name="username" /><div id="wrongUser"></div>
            <br />
        <input type="password" size="10" name="password" /><div id="wrongPass"></div>
            <br />
    <input type="submit" value="submit" name="submit" /><br /><br />
</form>

and these two functions:

function test()
{
    var user = document.login.username.value;
    var pass = document.login.password.value;
    if((user == "" || user == null) && (pass == "" || pass == null))
    {
        document.getElementById('wrongUser').innerText = "Please Enter Username";
        document.getElementById('wrongPass').innerText = "Please Enter Password";
        return false;
    }

    if(checkEmpty(user, 'wrongUser', "Please Enter Username"))
        return false

    if(checkEmpty(pass, 'wrongPass', "Please Enter Password"))
        return false;

    return true;
}

function checkEmpty(name, id, output)
{
    if(name == "" || name == null)
    {
        document.getElementById(id).innerText = "";
        document.getElementById(id).innerText = output;
        return true;
    }
    else
        return false;
}

Now the functions kinda work but not how I would think. If the user only doesn't enter anything (first time) then they get the 2 errors. If the user enter just a username (second time) then the username error should disappear, but it doesn't. If I take it out of the function and replace the variables with their normal values then it works just fine. Why would it change when put in this function?

2
  • 1
    As an aside, innerText is an IE-only property - I would check if textContent is supported and use that first (all browsers support it except IE < 9), then fall back to innerText. Commented Jan 15, 2012 at 8:16
  • Huh so it is. Works in latest version of Chrome Commented Jan 15, 2012 at 8:18

1 Answer 1

3

Put the document.getElementById().innerText = '' in the else, not in the if. Because you only reset the innerText when it's empty, but you would like to reset the tekst if it's not empty:

function checkEmpty( name, id, output ) {
  var elem = document.getElementById(id); // it's faster to put the element in a var

  if( name === undefined || name == '' name == null )
    elem.innerText = output;
    return true;
  else
    elem.innerText = '';
    return false;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh gotcha. I put it in my innerText='' in my else and it works for username but not password?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.