javascript - JS密码确认

标签 javascript html

我有一个简单的注册页面:

<html>
<head>
    <title>Register</title>
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
    <form action="">
        <div>
            <label style="display: block; padding-left: 0.3em;">REGISTER</label>
        </div>

        <div class="emailInputDiv">
            <label class="email">Email </label>
            <input type="text" name="email" id="em">
        </div>

        <div class="passwordInputDiv">
            <label class="password">Password</label>
            <input type="password" name="password" id="pw">
        </div>

        <div class="passwordInputDiv2">
            <label class="password">Confirm Password</label>
            <input type="password" name="password" id="pw2">
        </div>

        <div style="margin-bottom: 0.5em">
            <button type="submit" class="signInButton" onclick="check()">
                <span>Sign In</span>
            </button>
        </div>
    </form>


    <script>
        let pw = document.getElementById("pw").value;
        let pw2 = document.getElementById("pw2").value;
        (function () {
            if(pw != pw2){
                $('.passwordInputDiv').css("color", "red");
                $('.passwordInputDiv > input').css("color", "red");
                $('.passwordInputDiv2').css("color", "red");
                $('.passwordInputDiv2 > input').css("color", "red");
            }
        })();

    </script>
</body>
</html>

我想在密码输入更改且不匹配时立即将其字体颜色设置为红色。该自执行函数在页面加载时运行,但我希望它在每次输入更改时运行。

而且那些 pw 和 pw2 是空的,因为它在页面加载时执行。所以函数没有执行。

我该如何调整?

最佳答案

要在每次输入更改时运行 Javascript 函数,您可以将 oninput='exampleJavascriptFunction()' 添加到 HTML 元素或使用 Javascript 添加事件监听器,如下所述。

所以你的第一个密码框:

<input type="password" name="password" id="pw">

会变成:

<input type="password" name="password" oninput="check()" id="pw">

Note: It is now better a better practice to use a javascript function to add an event listener.

For example: element.addEventListener([name], [callback]) with plain Javascript or element.on([name], [callback]) with Jquery (which uses addEventListener internaly).

使用 Jquery/Javascript 添加事件监听器:

$("pw").on('input', check)

参见 Jquery onMDN input event

希望这对您有所帮助。

关于javascript - JS密码确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59344462/

相关文章:

javascript - 如何更新 Google map 引擎表?

javascript - 保持计时器在组件之间同步

php - 多个SQL查询来选择数据MySql php

javascript - 根据url滚动网页

css - 嵌套的 div 同样长

javascript - 查看容器破坏了我的代码

javascript - 如何从 String.prototype.replace() 方法中的回调返回正确的值?

javascript - key 代码 13 不起作用

javascript - 在 swift 中将 HTML 字符串解析为 JSON

javascript - 尝试将数字标签转换为 int