出现错误时添加CSS

时间:2013-05-04 10:22:07

标签: javascript css forms alert

我有一个简单的登录页面,我遇到了一些麻烦。当您输入不正确的信息时,它只会运行警报,但我希望它将一些CSS添加到使其变红的字段的背景中。我如何编辑以下代码来执行此操作?

Here's the fiddle.

感谢。

<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <title>Jeremy Blaz&eacute;</title>
</head>
<body>
    <div id="box">
        <img src="logo.png" />
        <form name="login">
            <input type="text" name="userid" placeholder="Username" />
            <input type="password" name="pswrd" placeholder="Password" />
            <input type="submit" class="button" onclick="check(this.form)" placeholder="Password" value="Sign in" />
        </form>
    </div>
    <script language="javascript">
    function check(form) {
        if(form.userid.value == "username" && form.pswrd.value == "password") {
            window.open('dashboard/index.html')
        }
        else {
            alert("Error Password or Username")
        }
    }
    </script>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

// js
else {
    alert("Error Password or Username");
    document.login.class = "error";
}

// css
form.error input[type="text"], form.error input[type="text"] {
    background-color: red;
}

答案 1 :(得分:0)

如果出错,您可以这样做:

form.userid.className = "invalid";

CSS

.invalid
{
    border-style:solid;
    border-width:2px;
    border-color:red;
}

答案 2 :(得分:0)

我会略微更改您的功能,并在表单onsubmit上运行:

function check(form) {

    var valid = true;

    if (form.userid.value !== 'username') {
        form.userid.className = 'error';
        valid = false;
    }
    else {
        form.userid.className = '';
    }

    if (form.pswrd.value !== 'password') {
        form.pswrd.className = 'error';
        valid = false;
    }
    else {
        form.pswrd.className = '';
    }

    if (valid) {
        window.open('dashboard/index.html');
    }

    return false; // return valid; if you want to submit the form once it's valid
}

HTML:

<form name="login" onsubmit="return check(this)">

CSS:

#box input.error {
    border: 1px darksalmon solid;
    background: #f0dddd;
}

演示:http://jsfiddle.net/JLrQB/1/