文本输入验证功能Javascript

时间:2015-12-02 17:25:20

标签: javascript html function input onclick

有人可以告诉我为什么我的代码无效吗? 我收到错误:无法读取null的属性'value'。

这是我的HTML代码:

<body onLoad="init()">
<input type="text" placeholder="User Name" id="id_inputuser"></input>
<label>Please Enter User Name</label><br>
<input type="text" placeholder="Password"id="id_inputpass"></input>
<label>Please Enter Password</label><br><br>

<button onClick="verify()">Enter</button>
</body>

这是JS:

function init()
{
var user= document.getElementById("id_inputuser").value;
function verify()
{if (user=="david")
{alert("working")}

else{alert("not working")};
}}

任何帮助都将受到高度赞赏:) 非常感谢!

2 个答案:

答案 0 :(得分:1)

如果你说这是完整的代码,那么这是有效的

<!DOCTYPE html>
<html>
<body>

<input type="text" placeholder="User Name" id="id_inputuser"></input>
<label>Please Enter User Name</label><br>
<input type="text" placeholder="Password"id="id_inputpass"></input>
<label>Please Enter Password</label><br><br>

<button onClick="verify()">Enter</button>

<script>

function verify()
{
var user= document.getElementById("id_inputuser").value;
if (user=="david")
{alert("working")}

else{alert("not working")};
}
</script>

</body>
</html>

答案 1 :(得分:0)

  1. 确保您发布的javascript代码段是在相关HTML之后定义的。
  2. var input...行移至verify()功能。
  3. e.g。

    <input type="text" id="username" />
    
    <script>
    function checkUsername () {
      var value = document.getElementByid('username').value;
    
      alert( value ? 'Valid' : 'Empty' );
    }
    
    document.getElementById('username').addEventListener('change', checkUsername);
    
    </script>
    
相关问题