I am new in Javascript and I want to make a code where a window will be open asking the user to type a specific password. If the password is correct then he "enters" the page. In the page, he can find an input and a button. He can change the password by filling the input and then pressing the Submit button. Basically to change the value of the variable. The problem is that I don't know how can I "pass" the input with id="changePass" to the variable pass1 and then I am not sure if the new password will be saved. Thank you in advance! Bellow you can find my code:
<html>
<body>
<script>
var entered = false;
var password;
var pass1="pass";
if (entered == false) {
password = prompt('Enter your password in order to view this page!', ' ');
if (password == pass1) {
alert('Correct Password, Enter the Club');
entered = true;
} else {
window.location = "";
}
} else if (entered == true) {
alert('You have already entered the password. Click OK to enter!');
}
</script>
<input id="changePass"/>
<button id="subimt" type"Submit">Submit</button>
</body>
</html>
My friend you can't rely on browser storage and cookies for logging in users and keeping passwords. The least of your problems is that if a user clears his cookies and history you are going to lose it all. :)
This is why I asked if it is a homework or at least something that you don't really care to hold on to user credentials, and your users won't have any problem to re-enter the default password every once a while.
With that being said below is the code you want to store the password to local storage
<input id="changePass"/>
<button id="changePassBtn" type"Button" onclick='changePassBtnClick()'>Change Password</button>
<input id="login"/>
<button id="loginBtn" type"Button" onclick='loginBtnClick()'>Login</button>
<script>
if(!localStorage.getItem('password')){
localStorage.setItem('password', 'pass');
}
function changePassBtnClick(){
localStorage.setItem('password', document.getElementById('changePass').value);
alert('Password changed');
}
function loginBtnClick(){
if(document.getElementById('login').value == localStorage.getItem('password')){
alert('Correct Login');
}else{
alert('Wrong Password');
}
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With