Reputation: 3986
I am using local storage to store credentials and login details. It is working fine but when i tried to change that value it is not changing.
Here is the code for login.
login.html
<script type="text/javascript">
window.localStorage.setItem("login", "true");
window.localStorage.setItem("email", data.email);
window.localStorage.setItem("id", data.uid);
window.localStorage.setItem("name", data.name);
</script>
and here is the code for logout. This one not working.
logout.html
window.localStorage.setItem("login", "false");
For some reason i am always getting login = true
in logout.html file.
Any advise what am i doing wrong.
Edit:
Nothing wrong with the code. It is working fine. I was accessing the file directly thats why it was not changing.
Upvotes: 0
Views: 3773
Reputation: 1334
This works for me. You must have something else going on that isn't working.
<script type="text/javascript">
localStorage.setItem("login", true);
alert(localStorage.getItem('login'));
localStorage.setItem("login", false);
alert(localStorage.getItem('login'));
</script>
Works with quotes as well.
<script type="text/javascript">
localStorage.setItem("login", "true");
alert(localStorage.getItem('login'));
localStorage.setItem("login", "false");
alert(localStorage.getItem('login'));
</script>
And here is checking...
<script type="text/javascript">
localStorage.setItem("login", "true");
if(localStorage.getItem("login")==="true"){
alert('Value is True')
}
localStorage.setItem("login", "false");
//login is false so this will not fire
if(localStorage.getItem("login")==="true"){
alert('Value is True')
}
</script>
Upvotes: 1
Reputation: 150
perhaps, you should use
JSON.parse(localStorage.getItem("login"))
this will get your item as a boolean true or false
Upvotes: 0
Reputation: 997
Have you tried removing the item?
window.localStorage.removeItem("login");
window.localStorage.setItem("login", "false");
Upvotes: 1
Reputation: 4809
a guess: you are using somehting like
if(window.localStorage.getItem("login"))
and its true. if that is the case its because any non empty string would yield true. if that is the case, try
if(window.localStorage.getItem("login")==="true")
or
if(window.localStorage.getItem("login")!=="false")
Upvotes: 1