I was trying to make a basic sign-up/login thingy using localStorage in JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>login</h1>
<h2>username</h2>
<input id = "userSave">
<h2>password</h2>
<input id = "passSave">
<button onclick = "saved()">save</button>
<h2 id = "textSave"></h2>
<h1>sign up</h1>
<h2>username</h2>
<input id = "userLoad">
<h2>password</h2>
<input id = "passLoad">
<button onclick = "loaded()">load</button>
<h2 id = "textLoad"></h2>
<script>
function saved() {
let text = document.getElementById("textSave").innerHTML;
let username = document.getElementById("userSave").value;
let password = document.getElementById("passSave").value;
localStorage.setItem(username, password);
text = "saved";
}
function loaded() {
let text = document.getElementById("textLoad").innerHTML;
let username = document.getElementById("userLoad").value;
let password = document.getElementById("passLoad").value;
if (localStorage.getItem(username) == password) {
text = "welcome";
}
else {
text = "login failed";
}
}
</script>
</body>
</html>
I have checked everything. Spelling, onclicks, function names, and most of the stuff is fine, but it won’t work properly
2
Answers
I assume what you mean with "it doesn’t work", is that you don’t see any DOM changes. Strings are immutable so it counts as a "pass by value".
If you want to make DOM changes, then instead set your text reference to the element:
Side note: I realize this is for practise, so I won’t dig to deep into it – but storing passwords as plaintext, and on the client (and doing client validation for passwords) is never a good idea for any real projects
first thing do you need is fix your logic for login and sign up flow. You can separated this with 2 different page. usually, we can login if we have an account (Username or Password) and sign up if we haven’t username and password.
You can see bellow logic for login like
And A Sign Up Like:
I hope this help you to find solution.