Reputation: 65
How am I able to store the original password to my local storage?
I have two inputs username and password:
<input id="myInput" type="text" name="myInput" placeholder="Input">
<input id="myPW" type="password" name="myPassword" placeholder="Password">
What I want to do in my javascript is to store my username, password converted to Base64, and the original data of password. But it only store the username and Base64 password. The original password won't stored. How am I able to fix it?
Upvotes: 1
Views: 339
Reputation: 790
You inpw is emty after line inpw.value = "";
In addition, don't repeat your self. I do some refactor. You should write functions to get the credential to localstore like
const storedValue = ['user', 'pass', 'origin']
const credential = getCredentialFromStore(storedValue)
const getCredentialFromStore = (storedValue) => {
const result = []
storedValue.forEach(item => {
result[item] = localStorage.getItem(item) ? JSON.parse(localStorage.getItem(item)) : [];
})
return result
}
And also write some function to set the credential to localstore like
const addToCredential = (credential, key, value) => {
credential[key].push(value);
localStorage.setItem(key, JSON.stringify(credential[key]));
return credential
}
Using :
addToCredential(credential, 'user', inp.value)
addToCredential(credential, 'pass', window.btoa(inpw.value))
addToCredential(credential, 'orig', inpw.value)
Upvotes: 1
Reputation: 6728
Because you set inpw.value
to empty string before using it to push the original password.
userArray.push(inp.value);
localStorage.setItem('user', JSON.stringify(userArray));
inp.value = "";
passArray.push(window.btoa(inpw.value));
localStorage.setItem('pass', JSON.stringify(passArray));
inpw.value = ""; // This makes next inpw.value equals ""
origPassArray.push(inpw.value); // So this will push an empty string to the array
localStorage.setItem('orig', JSON.stringify(origPassArray));
inpw.value = "";
Upvotes: 2