2015-12-02 109 views
0

有人可以告诉我为什么我的代码不工作吗? 我收到错误:无法读取null的属性'值'。文本输入验证功能Javascript

这是我的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")}; 
}} 

任何帮助将不胜感激:) 非常感谢!

+0

被调用_JavaScript_什么时候?当时是否存在''_Element_? –

+0

把'var user = document.getElementById(“id_inputuser”).value;'放入你的函数中。另外,输入是自闭的。 – j08691

+0

谢谢@ j08691,但现在我得到的错误:意外的令牌var 登录和init未定义。 我有一个onload函数caled init,并且验证函数在里面。 – user3185970

回答

0
  1. 确保您发布的javascript代码段是在相关HTML之后定义的。
  2. var input...行移入verify()函数内。

例如

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