I have a log in page that is asking for a username and a password. I want to check it against the local storage that adds and stores an object of user data (one object = username, full name, password, postcode, email, mobile). I have this so far that I want to try it out and test it, but I keep getting 'undefined
' when I get the console to print the username and password that the user has input into the log in screen. I can't figure out why?
Here's my js:
const loginForm = document.querySelector(".login-form");
let usernameInput = document.getElementsByClassName(".lg-username").value;
let passwordInput = document.getElementsByClassName(".lg-password").value;
loginForm.addEventListener("submit", (e) => {
e.preventDefault();
if (localStorage.getItem("UserData")) {
const data = JSON.parse(localStorage.getItem('UserData'))
if(usernameInput === data.username && passwordInput === data.password) {
console.log("ye");
}else{
console.log("ne");
}
}else{
console.log("not regis");
}
console.log("not nice");
console.log(localStorage);
console.log(usernameInput);
console.log(passwordInput);
})
<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">
<div >
</form>
CodePudding user response:
First, the class name is not correct .lg-username
and .lg-password
not exist, it should be .username
and .password
.
Second, you should use querySelector
instead of getElementsByClassName
to get the first element which has the class, but getElementsByClassName
get a HTMLCollection
Third, you need to get the value when you submit not when the script load.
const loginForm = document.querySelector(".login-form");
let username = document.querySelector(".username");
let password = document.querySelector(".password");
loginForm.addEventListener("submit", (e) => {
e.preventDefault();
if (localStorage.getItem("UserData")) {
const data = JSON.parse(localStorage.getItem('UserData'))
if(username.value === data.username && password.value === data.password) {
console.log("ye");
}else{
console.log("ne");
}
}else{
console.log("not regis");
}
console.log("not nice");
console.log(localStorage);
console.log(username.value);
console.log(password.value);
})
<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">
<div >
</form>