0

Can someone please tell me why my code isn't working? I get the error: Cannot read property 'value' of null.

This is my html code:

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

And this is the JS:

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

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

Any help will be highly appreciated :) Thanks a lot!

8
  • When is the JavaScript being invoked? Does the <input> Element exist at that time? Commented Dec 2, 2015 at 17:26
  • Put var user= document.getElementById("id_inputuser").value; within your function. Also, inputs are self-closing. Commented Dec 2, 2015 at 17:26
  • Thanks @j08691, but now i get the errors: Unexpected token var login and init is not defined. I have an onload function caled init, and the verify function is in it. Commented Dec 2, 2015 at 17:30
  • 1
    You have no code in your question that contains vars login or init. Commented Dec 2, 2015 at 17:31
  • Please update your question with a complete code example instead of posting it in a comment. Commented Dec 2, 2015 at 17:34

2 Answers 2

1

if you say this is the complete code then this is working

<!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>
Sign up to request clarification or add additional context in comments.

Comments

0
  1. Make sure the javascript snippet you posted is defined AFTER the relevant HTML.
  2. Move the var input... line inside the verify() function.

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>

Comments

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.