Rudi
Rudi

Reputation: 249

javascript for loop dosn't loop through users created

OK so I am making a register and login for a forum using javascript and localstorage. "School assignment" My problem is that when i created multiple user and store them in the localstorage, my for loop does not loop through them all, only the first one. So i can only access the forum with the first user i create.

function login ()  {
    if (checklogin()) {
        boxAlert.style.display = "block";
        boxAlert.innerHTML = "Welcome" + "";
        wallPanel.style.display = "block";
    } else {
        boxAlertfail.style.display = "block";
        boxAlertfail.innerHTML = "Go away, fail";
    }
}

function checklogin (){
    for  (var i = 0; i < aUsers.length; i++){
        if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value){
            return true;
        }else{
            return false;
        }
    }
}

Upvotes: 0

Views: 81

Answers (2)

jcera
jcera

Reputation: 345

how about:

function checklogin() {
    var validLogin = false;
    for (var i = 0; i < aUsers.length; i++) {
        if (aUsers[i].email == inputLoginMail.value 
            && aUsers[i].password == inputLoginPassword.value) {
            validLogin = true;
            break;
        }
    }
    return validLogin;
}

Upvotes: 1

mehulmpt
mehulmpt

Reputation: 16597

Ouch! You are returning false on very first attempt. The best way is to set a variable and then check for it.

function checklogin() {
        var z = 0;
        for (var i = 0; i < aUsers.length; i++) {
            if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value) {
                z = 1;
                break;
            } else {
                z = 0;
            }

            if (z == 1) {
                // User logged in
            } else {
                // Fake user
            }
        }

Upvotes: 0

Related Questions