Javascript - 值不传递给函数

时间:2012-01-15 08:00:11

标签: javascript html css forms validation

所以我有这样的表格:

<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>

和这两个功能:

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;
}

现在功能有点起作用,但不是我的想法。如果用户只输入任何内容(第一次),则会出现2个错误。如果用户只输入用户名(第二次),那么用户名错误应该消失,但事实并非如此。如果我把它从函数中取出并用它们的正常值替换变量那么它就可以了。放入此功能时为什么会改变?

1 个答案:

答案 0 :(得分:3)

document.getElementById().innerText = ''放入else中,而不是if中。因为你只在内部空文本为空时才重置它,但如果它不是空的你想重置它:

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;
}