Reputation: 27
I have no idea why this does not work. I've seen similar problems on so but they don't fix the problem
That's the HTML code
<html>
<head>
<meta charset="utf-8" />
<title>Java Script 2</title>
</head>
<body>
<div id="loginForm">
<form name="userLogin">
<input type="text" name="userName" />
<input type="password" name="userPass" />
<input type="button" name="login" value="Login" />
</div>
<script src = "question_2.js"></script>
</form>
</div>
</body>
</html>
and this is the JavaScript
var submit = document.getElementById("login");
if(submit!="null"){
submit.addEventListener("click",getLogin);
}
function getLogin(){
var nameData = "admin";
var passData = "admin";
var userName = document.userLogin.userName.value;
var pass = document.userLogin.userPass.value;
if(userName.compareTo(nameData) && pass.compareTo(passData)){
replace.textContent("Hello there " + nameData);
}
else{
document.write("Try again");
}
}
I have to make the page remove the sign in from when it matches the set login and password to remove the form and display a welcome message. When i open the page and go into the console I get the following error
Uncaught TypeError: Cannot read property 'addEventListener' of nullquestion_2.js:4 (anonymous function)
It targets the action listener I have set for the button but I have no idea how to fix this.
Upvotes: 1
Views: 25820
Reputation: 3591
From your HTML code above, you did not define the ID you making reference to.
you made reference to ID (login
) on this line var submit = document.getElementById("login");
While the only Id
you had in the HTML
was "loginform"
.
you can correct that line or simply add the "login"
Id to the desired HTML
attribute and it will surely work as desired.
Upvotes: 0
Reputation: 1
just simply add defer to your script src at .html like
<script src="slide 52.js" defer></script>
Upvotes: 0
Reputation: 1380
Well, you have no Element with the id:"login". Thats why submit is null.
You should give the input:
<input type="button" name="login" value="Login" />
the appropriate id. And, another thing:
if(submit!="null")
I assume you want to check "submit" against the actual value: null, not the string "null". You should write your if-statement it as follows:
if(submit!==null)
This way, you check submit against the null-Object, and you do it type-safe, that means if sumbit is not null, but for some strange reason undefined, you will still do the correct check. Read Steve Johnsons Blog Post on undefined vs. null, if this is somehow new to you.
Upvotes: 3
Reputation:
You have no element with ID "login"
var submit = document.getElementById("login");
if(submit){
submit.addEventListener("click",getLogin);
}
Upvotes: 1