简体   繁体   中英

Why am I getting the “Cannot set property 'border' of undefined” error?

I am getting the "Cannot set property 'border' of undefined" error on line 6 of my JavaScript code. I want to be able to change the CSS of the username textbox so that the border color is different. How can I go about fixing this?

HTML:

<!DOCTYPE html>

<html>
    <head>
        <title>Login Screen</title>
        <link rel="stylesheet" type="text/css" href="login.css"/>
        <script src="login.js"></script>
    </head>

    <body>
        <div id="container">
            <h1 onclick="loginDetails()">Login</h1>
            <form onsubmit="return validateLogin()">
                <label for="username" class="label-1">Username</label><br>
                <input type="text" id="username" class="text-box"><br>
                <label for="password" class="label-2">Password</label><br>
                <input type="text" id="password" class="text-box"><br>
                <button type="submit" id="login" class="button">Sign In</button>
            </form>
        </div>
    </body>
</html>

CSS:

#username {
    border: 1px solid gray;
}

JavaScript:

function validateLogin() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    if (username.length < 5) {
        username.style.border = "1px solid red";
        return false;
    }
}

You're attempting to set a CSS property on the value of the input field.

Replace with:

function validateLogin() {
    var username = document.getElementById("username");
    var password = document.getElementById("password");

    if (username.value.length < 5) {
        username.style.border = "1px solid red";
        return false;
    }
}

Example codepen: https://codepen.io/jmitchell38488/pen/xxZOMoQ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM