checkValidity
is a predefined method, which means that your function is being overshadowed by it and not executing as expected. To resolve this issue, there are two possible solutions - one that simply works and another that is considered superior.
The first solution involves renaming your function to avoid conflicts with the existing method.
The second solution entails refraining from using inline attribute assignment to handle events, opting instead for addEventListener
. Not only does this approach provide various advantages (refer to References), but it also ensures smooth functioning of the code snippet provided below:
const pass = '2207'
const button = Array.from(document.getElementsByTagName("button"))[0];
button.addEventListener("click", checkPassword);
function checkPassword() {
const pass_code = document.getElementById("passcode").value;
if (pass_code == pass){
alert("Correct Passcode!");
}
else{
alert("Wrong Passcode!");
}
}
<!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>Enter↵</button>
</div>
<script src = "script.js"></script>
</body>
</html>
1 The statement suggesting that checkValidity
is a reserved word has been corrected by Jaromanda.
P.S. It is advisable to refrain from using inline styling and instead opt for internal or external CSS according to best practices.
P.S. 2 Additionally, following established conventions, variable names should not begin with a capital letter unless they denote a class or constructor.
References