Reputation: 37233
I couldnt make this to work and to save variable when page refreshes.
here what im using.
window.onload = function () {
if (localStorage.getItem("forg") === null) {
localStorage.getItem("forg2");
} else {
localStorage.getItem("forg");
}
}
function forgot() {
$('#pass_icon').removeClass("pass-icon");
$('#forgot').replaceWith('<input class="login_register" id="forgot2" type="button" value="' + login + '" />');
}
function forgot2() {
$('#pass_icon').addClass("pass-icon");
$('#logintitle').html('<h1>' + login_form + '</h1>');
}
$(document).on('click', '#forgot', function () {
forgot();
localStorage.removeItem("forg2");
localStorage.setItem("forg", forgot());
});
$(document).on('click', '#forgot2', function () {
forgot2();
localStorage.removeItem("forg");
localStorage.setItem("forg2", forgot2());
});
this code doesnt save and when page reloads im getting function forgot()
by default .
what i want is when i click on #forgot2
then when page refreshes it will stay this function forgot2()
.
i dont know what im doing wrong here.
I have latest version of firefox(27).
Upvotes: 0
Views: 3639
Reputation: 707158
These two lines of code look like your problem:
localStorage.setItem("forg", forgot());
and
localStorage.setItem("forg2", forgot2());
I don't know what you're trying to do, what these two lines of code are doing is calling those two functions immediately and then trying to put the return result from those functions into localStorage. Since neither of the functions has a return value, you're trying to put undefined
into localStorage. Obviously, that won't accomplish anything useful other than wiping out what was previously in LocalStorage for that item.
If what you were trying to do is to put a function in localStorage, that isn't something you can do. localStorage accepts strings. You need to store a string there and you can then examine that string at some future time and change your logic based on the string you find in localStorage.
So, for example, you could store one of two strings in localStorage: "forgot"
or "forgot2"
. Then, when you retrieve an item from localStorage, you can check with an if
statement to see which string you found and then execute different code based on the result of the if
statement. First off, you probably only need one key in localStorage and you can use different values for that single key. Here's an idea how you would read it:
var storageVal = localStorage.getItem("forg");
if (storageVal) {
if (storageVal === "forget") {
// code here for the "forget" state
} else if storageVal === "forget2" {
// code here for the "forget2" state
}
}
$(document).on('click', '#forgot', function () {
forgot();
localStorage.setItem("forg", "forget");
});
$(document).on('click', '#forgot2', function () {
forgot2();
localStorage.setItem("forg", "forget2");
});
Upvotes: 2