I have a really weird error in my code that I just cannot figure it out. Basically, I'm making a simple username save/recall form. I take in input from a user and save it into a localstorage of browser. After, when I try to access with the input from before, I would recall the item from the localstorage.
My if statement doesn't seem to work. I tried comparing items individually - I tried comparing "document.getElementById('userName')" with a random string and "localStorage.getItem('login_info')" vice versa. However, when I try to do
if (localStorage.getItem('login_info') === document.getElementById('userName'))
The code would never return true as an output. any ideas? Thanks!
<!DOCTYPE html>
<html>
<head>
<title>Try</title>
</head>
<body>
<p> Please type in your username and password </p>
<form id="register_form">
<input id="name1" type="text" placeholder="Name" value=""/>
<input id="rgstr_btn" type="submit" value="Register" onClick="store()"/>
</form>
<form name="login">
<input id="userName" type="text" placeholder="Enter Username" value=""/>
<input id="login_btn" type="submit" value="Login" onClick="check()"/>
<input type="reset" value="Cancel"/>
</form>
<script type="text/javascript">
var user_name = document.getElementById('name1');
function store(){
localStorage.setItem('login_info', user_name.value)
}
function check(){
var storedName = localStorage.getItem('login_info');
// entered data from the login form
var user_Name = document.getElementById('userName');
if (document.getElementById('userName') === localStorage.getItem('login_info')){
alert("Login Successful! Continuing to ..");
window.open("Us.html");
}
else{
alert("Login unsuccessful, please try again!");
}
}
</script>
<noscript> Please try a different browser! </noscript>
</body>
</html>