Reputation: 13
I am trying to make a HTML and JS Sign up that will store the login details in LocalStorage. I have a class with 2 parameters, one of them is the password.
Then I have a function that will create an object through that class and will store it in local storage.
I need that the name of the object is the username (input id="username_r"
).
My problem is that when I do console.log(user1)
for example, the output is [object Object]
class user {
constructor(status, password) {
this.status = status;
this.password = password;
}
}
function signup() {
pw = document.getElementById("password_r").value;
window[document.getElementById("username_r").value] = new user("active", pw);
localStorage.setItem(document.getElementById("username_r").value, window[document.getElementById("username_r").value]);
}
<div class="form">
<input type="text" name="username" id="username_r" placeholder="Utilizador" required>
<br>
<br>
<input type="password" name="password" id="password_r" placeholder="Password" required>
<br>
<br>
<button id="registar" onclick="signup()">Criar Conta!</button>
</div>
Upvotes: 0
Views: 100
Reputation: 5205
I put some sample string values and while storing just stringified
the object. Then get the key and parse it. This is working.
class user {
constructor(status, password) {
this.status = status;
this.password = password;
}
}
function signup() {
pw = "myPwd";
window["user"] = new user("active", pw);
console.log(window["user"]);
localStorage.setItem("user",JSON.stringify(window["user"]) ); //Stringygy the object
};
signup();
var x = localStorage.getItem("user");
var myUser = JSON.parse(x); //This will give you the data of window['user']
Upvotes: 0
Reputation: 24965
If you want to stick with using the class, then what you could do is override the toString()
method to create the json form of the element. And you can store that in localStorage. Then when you need your class instance again, you would have to parse the json and create the element again from the data. To centralize that logic, you could make a static method on the class that performs that logic as well.
class user {
constructor(status, password) {
this.status = status;
this.password = password;
}
static build(json) {
var temp = JSON.parse(json);
return new user(temp.status, temp.password);
}
toString() {
return JSON.stringify({
status: this.status,
password: this.password
});
}
}
var user1 = new user('admin', 'nimda');
// force the usage of the `toString` method for show
console.log('My user: '+ user1);
var storedString = user1.toString();
console.log(storedString);
// use a static method to re-build the instance
var user2 = user.build(storedString);
console.log(user2);
Upvotes: 1