I have a sign up form that asks for 6 details to create a user object, but I only need 2 of those details for a user to log in (username and password). I couldn't figure out how to only get those 2 values from an object (comprised of 6 values) in the local storage, so I've made a separate array that holds those 2 required values (userLogin) and only added that to the local storage.
In the log in form, I'm trying to get it to see if my username and password input matches what has been stored, however I'm getting "ne" in the console, indicating that its not recognising a match. I've tried numerous ways of doing it and wording it, but I can't seem to get it to work. I think the problem is that I'm not actually getting the items that I need, but I'm not entirely sure. Please have a look.
// Sign up page
const login = document.querySelector(".login");
const loginSubmit = document.querySelector(".loginSubmit");
let users = [];
let user = {};
let userLogin = [];
signupForm.addEventListener("submit", (e) => {
e.preventDefault();
user = Object.fromEntries( [...document.querySelectorAll(".signup ul input")].map(e =>[e.name, e.value]));
users.push(user);
userLogin.push(user.username);
userLogin.push(user.password);
localStorage.setItem('UserData', JSON.stringify(userLogin));
console.log(localStorage);
});
// Log in page
const loginForm = document.querySelector(".login-form");
loginForm.addEventListener("submit", (e) => {
let usernameInput = document.querySelector(".lg-username").value;
let passwordInput = document.querySelector(".lg-password").value;
e.preventDefault();
if (localStorage.getItem("UserData")) {
const dataUsername = JSON.parse(localStorage.getItem('UserData', 'username'));
const dataPassword = JSON.parse(localStorage.getItem('UserData', 'password'));
if(usernameInput === dataUsername && passwordInput === dataPassword) {
console.log("ye");
}else{
console.log("ne");
}
}else{
console.log("not regis");
}
console.log(localStorage)
});
html signup form:
<form >
<ul>
<li><input type="text" name="username" placeholder="Username" required /></li>
<li><input type="text" name="fullname" placeholder="Full Name" required /></li>
<li><input type="email" name="email" placeholder="Email Address" required pattern=". @gmail\.com" /></li>
<li><input type="text" name="phone" placeholder="Phone Number" required /></li>
<li><input type="text" name="postcode" placeholder="Post Code" required /></li>
<li><input type="password" name="password" placeholder="Enter a password" required /></li>
</ul>
<input type="submit" >
</form>
html log in form:
<form >
<ul>
<li><input type="text" name="username" placeholder="Username" required></li>
<li><input type="password" name="password" placeholder="Password" required></li>
</ul>
<input type="submit" >
</form>
CodePudding user response:
Your answer is nearly correct.
Take this example:
localStorage.setItem('UserData', JSON.stringify(['test-username', 'test-pw']));
This will set an array to localstorage with key of 'UserData'.
We can get the values like this.
const [username, password] = JSON.parse(localStorage.getItem('UserData'));
CodePudding user response:
I couldn't quite figure out the way I wanted to do it, but instead of finding an item in a list in the local storage, I had it search the string in the local storage and see if it matched the user inputs. Like so:
// Sign up page; stores user input
const login = document.querySelector(".login");
const loginSubmit = document.querySelector(".loginSubmit");
let users = [];
let user = {};
let userLogin = [];
signupForm.addEventListener("submit", (e) =>{
e.preventDefault();
user = Object.fromEntries( [...document.querySelectorAll(".signup ul input")].map(e =>[e.name, e.value]));
users.push(user);
userLogin.push(user.username);
userLogin.push(user.password);
signupForm.innerHTML = `Thank you for joining ${user.fullname}!`;
signupForm.style.fontSize = '1.3rem';
signupForm.style.fontFamily = 'Segoe UI, Tahoma, Geneva, Verdana, sans-serif';
signupForm.style.textAlign = 'center';
signupForm.style.marginTop = '55%';
signupForm.style.fontWeight = 'bold';
localStorage.setItem('UserData', JSON.stringify(userLogin));
console.log(localStorage);
});
// Log in page; matches user input to sign up storage
const loginForm = document.querySelector(".login-form");
loginForm.addEventListener("submit", (e) => {
let usernameInput = document.querySelector(".lg-username").value;
let passwordInput = document.querySelector(".lg-password").value;
let loginData = [];
e.preventDefault();
if (localStorage.getItem("UserData")) {
loginData.push(usernameInput);
loginData.push(passwordInput);
const signupData = JSON.parse(localStorage.getItem('UserData'));
if(signupData.includes(usernameInput && passwordInput)) {
console.log("ye");
}else{
console.log("ne");
}
}else{
console.log("not regis");
}
});
CodePudding user response:
while you were updating your post, I found an old login code of mine
const loginForm = document.forms['login-form'] // use the form parent to refer each form elements
//// ----------- init part on page load. ----------- -----------
loginForm.reset() // clear loginForm to set elements initial values="" (empty)
const
loginDefault = JSON.stringify(Object.fromEntries(new FormData(loginForm).entries()))
, userLogin = JSON.parse( localStorage.getItem('UserData') || loginDefault )
;
Object.entries(userLogin).forEach(([key,val])=>
loginForm[key].value = val) // set user form login values from local storage
//// ----------- ----------- ----------- ----------- -----------
loginForm.onsubmit = evt =>
{
// get user login values:
Object.assign(userLogin, Object.fromEntries(new FormData(loginForm).entries()) )
// savein localstorage:
localStorage.setItem('UserData', JSON.stringify(userLogin))
// control part (only in testing)
console.clear()
console.log( loginForm.username.value, loginForm.user_psw.value ) // access each element by his name
console.log( JSON.stringify( userLogin ) )
evt.preventDefault(); // just for testing disable page submit / and relaod
}
if you want to test css html
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 16px;
}
fieldset {
margin : 2rem auto;
width : 12rem;
}
legend {
font-weight : bold;
font-size : 1.4rem;
margin-bottom : .2rem;
}
fieldset *:not(legend) {
display : block;
float : left;
clear : both;
margin-top : 0.2rem;
}
fieldset label {
margin-top : 0.8em;
font-size : .9rem;
}
fieldset button {
margin-top : 1.4rem;
width : 5.2rem;
}
fieldset button:last-of-type {
clear : none;
float : right;
}
<form name="login-form">
<!-- have a name (or an id) here -->
<fieldset>
<legend> Login form </legend>
<label>Name:</label>
<input type="text" name="username" autocomplete="off"
pattern="[A-Za-z0-9]{1,20}" placeholder="login name"
value="" required>
<label>Password:</label>
<input type="password" name="user_psw"
pattern="[A-Za-z0-9]{1,20}" placeholder="password"
value="">
<!--
<label>4-digit PIN:</label>
<input type="text" name="pinCode" autocomplete="off"
pattern="[0-9]{4}" placeholder="identification code"
value="" required>
-->
<button type="reset">clear</button>
<button type="submit">Log In</button>
</fieldset>
</form>