clydewinux
clydewinux

Reputation: 515

Javascript global variable is not updating

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 update the global variable and display the new value by alert, and second a function that will just alert the new value of the updated global variable. The problem now is when I call the first function, it alerts the new updated value, but when I call the second function it alerts the original value which is zero.

Here's my code:-

 var i=0; var users=new Array(); 
 var password=new Array(); 
 users[0]="clydewinux";
 password[0]="moonfang";
 users[1]="freddipasquale";
 password[1]="evastar182";

 function verifyInput() {   //function one
    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++;
            alert(i);
            window.location.replace("login.htm");
            break;
        } else {
            document.getElementById("username").value = "Invalid username...";
            window.location.href("home.htm");
            break;
        }
    }
}

function logout() {  //function two
    alert(i);
    window.location.replace("home.htm");
}

*Note; function verifyInput() is the first function, and function logout is the second.

Upvotes: 1

Views: 4455

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

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";

Upvotes: 2

Related Questions