用于文本框的asp.net onkeyup事件

时间:2017-07-21 09:06:53

标签: c# asp.net webforms textbox

我在使用textbox的onkeyup事件时遇到问题。我的功能是检查密码文本框的密码强度。因此,当用户输入密码时,如果密码非常弱/弱/中/强,它将调用检查密码强度的功能并在标签中显示。此外,文本框背景将根据密码的强度显示颜色。但是当我输入密码文本框时,标签不会显示任何内容,文本框也不会改变颜色。

<asp:TextBox ID="tb_password" runat="server" TextMode="Password" onKeyUp="checkPasswordStrength()"  ></asp:TextBox>
                        <script type="text/javascript">
    function checkPasswordStrength()
    {
        var passwordTextbox = document.getElementById("tb_password");
        var password = passwordTextbox.value;
        var specialCharacters = "!@#$%^&*_+";
        var passwordScore = 0;

        for (var i = 0; i < password.length; i++)
        {
            if(specialCharacters.indexOf(password.charAt(i) > -1))
            {
                passwordScore += 20;
            }
        }

        if (/[a-z]/.test(password))
        {
            passwordScore += 20;
        }

        if (/[A-Z]/.test(password)) {
            passwordScore += 20;
        }

        if (password.length >= 8) {
            passwordScore += 20;
        }

        if (/[\d]/.test(password)) {
            passwordScore += 20;
        }

        var strength = "";
        var backgroundColor = "";

        if (passwordScore >= 100)
        {
            strength = "Strong"
            backgroundColor = "green";
        }

        else if (passwordScore >= 80)
        {
            strength = "Medium"
            backgroundColor = "yellow";
        }

        else if (passwordScore >= 60) {
            strength = "Weak"
            backgroundColor = "red";
        }

        else
        {
            strength = "Very Weak"
            backgroundColor = "maroon";
        }

        document.getElementById("lbl_passwordStrength").innerHTML = strength;
        passwordTextbox.style.color = "white";
        passwordTextbox.style.backgroundColor = backgroundColor;
    }

</script>
                        <br />
                        <asp:Label ID="lbl_passwordStrength" runat="server"></asp:Label>

1 个答案:

答案 0 :(得分:0)

ASP.NET网页中包含的每个控件都必须包含唯一标识符(ID)。为了保持这种独特性,当页面呈现为HTML时,ASP.Net会更改控件的ID。

此处,如果以下控件位于<asp:ContentPlaceHolder>内,则ID可能会更改为ctl00$ctl00$ContentPlaceHolder$tb_password

<asp:TextBox ID="tb_password" runat="server" TextMode="Password" onKeyUp="checkPasswordStrength()"></asp:TextBox>

要解决此问题,您可以在标记中使用客户端模式,或在javascript中使用 ClientID

  

方法1:

<asp:TextBox ID="tb_password" runat="server" TextMode="Password" onKeyUp="checkPasswordStrength()" ClientMode="Static"></asp:TextBox>
  

方法2:

var passwordTextbox = document.getElementById("<%=tb_password.ClientID%>");
.
.
.
.
document.getElementById("<%=lbl_passwordStrength.ClientID%>").innerHTML = strength;
passwordTextbox.style.color = "white";
passwordTextbox.style.backgroundColor = backgroundColor;