**This is the HTML Part**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body style="background-color: rgb(0, 255, 195); text-align: center">
<div id="display">
<p style="color:black">Enter your Passcode:</p>
<input id="passcode" type = "password">
<button onclick="checkValidity()">Enter↵</button>
</div>
<script src = "script.js"></script>
</body>
</html>
**This is the JAVASCRIPT Part**
const Pass = '2207'
function checkValidity(){
const pass_code = document.getElementById("passcode").value;
if (pass_code == Pass){
alert("Correct Passcode!");
}
else{
alert("Wrong Passcode!");
}
}
*****The checkValidity function does not work and there is no alert dialogue box that appears, I want so that the passcode entered by the user is compared with the constant "Pass" *****
2
Answers
checkValidity
is an existing method, so it is a reserved word. That’s why your function is not running. So two solutions: one that works and one that is even better.The first one is simply to rename your function. Voilà.
The second one is this: avoid handling events through inline attribute assignment, and use
addEventListener
instead. It has several advantages (see References). The following code works perfectly:P.S. Also avoid inline styling, and use internal/external CSS instead.
P.S. 2 As I said in my comment, variable names shouldn’t start with a capital letter (unless you’re declaring a class or constructor).
References
The problem is that you are using a reserved word to name your function. I tried changing the name of the function and it works.
Another problem is also the usage of a capitalized P for Pass variable. Try to use a lowercase
p
when naming variables. Also, use'==='
instead of'=='
as it also comparetypes
(in your case both types are string, but just in case, use '==='.)