I have this site that I am making. I want to update a global variable from another function. The global variable i
is initialized to 0. I created 2 functions, 1 to
When you call the first function, you change the page content by loading a new page.
Javascript variables aren't kept from one page to another one.
So i
is a new value after you called window.location.replace
or window.location.href=
.
If you want to keep some values from one page to another one, you may use localStorage
:
var i = parseInt(localStorage['i'] || '0', 10); // loads the old saved value of i
function verifyInput() {
var u = login.username.value;
var p = login.password.value;
for (var c = 0; c <= 1; c++) {
if (u === users[c] && p === password[c]) {
i++;
localStorage['i'] = i; // stores the incremented i
alert(i);
window.location.replace("login.htm"); // this ends the script and reload the page
break; // this is useless : the script has ended
} else {
document.getElementById("username").value = "Invalid username...";
window.location.href("home.htm"); // this is buggy
break;
}
}
}
function logout() {
alert(i);
window.location.replace("home.htm");
}
Side note : window.location.href("home.htm");
wouldn't work : use window.location.href = "home.htm";