Dean Hampson
Dean Hampson

Reputation: 77

Adding new values to objects

I have an array object and would like it so I can add additional username and passwords of different users. If the username or password does not exist, it'll create it automatically. I thought my array object would work like this: userInfo[0]["username"] is user1, userInfo[1]["username"] is user2, etc. Here is the jsfiddle: https://jsfiddle.net/xkxn54bx/

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <script src="test.js"></script>
    <title>Generation X</title>
</head>
<body>
    <form method="post">
    <label for="username">Username:</label><input type="text" name="user_name" id="username"><br />
    <label for="password">Password:</label><input type="password" name="pass-word" id="password">
    <input type="submit" id="submitbutton" value="Access">
    </form>
</body>
</html>

JS:

var userInfo = [
    { username: "admin", password: "test" }
];

function addUser(username, password) {
    userInfo[userInfo.length + 1]["username"] = username;
    userInfo[userInfo.length + 1]["password"] = password;
}

$(document).ready(function() {
    $('#submitbutton').click(function() {
        var username = $('#username').val();
        var password = $('#password').val();
        for (i = 0; i < userInfo.length; i++) {
            if (username == '' || password == '') {
                alert("All fields are required!");
            }
            else if (username == userInfo[i]["username"]) {
                if (password == userInfo[i]["password"]) {
                    alert("Welcome");
                }
                else {
                    alert("You have entered an invalid password!");
                }
            }
            else {
                addUser(username, password);
                alert("Account created!");
            }
        }
    });
});

Upvotes: 0

Views: 77

Answers (1)

Sean12
Sean12

Reputation: 847

I'm not sure if you are accessing the array correctly, when adding new objects to it. It should be as:

function addUser(username, password) {
    userInfo[userInfo.length - 1]["username"] = username;
    userInfo[userInfo.length - 1]["password"] = password;
}

Since length is always one more than the last index and that's the index that you want to populate with the new object. If you instead use:

userInfo[userInfo.length + 1]["username"] = username;

Then you are skipping one index. Also, it is a good idea to create an object at that index first:

function addUser(username, password) {
    userInfo[userInfo.length]={};

    userInfo[userInfo.length - 1]["username"] = username;
    userInfo[userInfo.length - 1]["password"] = password;
}

Upvotes: 1

Related Questions