Reputation: 3
I have an issue with onkeyup event with textbox. my function is to check password strength of the password textbox. so when a users enter his password, it will call the function of checking password strength and show in a label if his password is very weak/weak/medium/strong. Also, the textbox background will show colors according to the strength of the password. however when i type in the password textbox, the label does not show anything and the textbox does not change color.
<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>
Upvotes: 0
Views: 16546
Reputation: 3216
Every control that is included in an ASP.NET Web page must contain a unique identifier (ID). To maintain this uniqueness ASP.Net change the ID of control when the page gets rendered into HTML.
Here, if below control is inside <asp:ContentPlaceHolder>
then the ID is likely to gets changed into ctl00$ctl00$ContentPlaceHolder$tb_password
for example.
<asp:TextBox ID="tb_password" runat="server" TextMode="Password" onKeyUp="checkPasswordStrength()"></asp:TextBox>
To overcome this what you can do it either use Client Mode in mark-up or use ClientID in javascript.
Method 1:
<asp:TextBox ID="tb_password" runat="server" TextMode="Password" onKeyUp="checkPasswordStrength()" ClientMode="Static"></asp:TextBox>
Method 2:
var passwordTextbox = document.getElementById("<%=tb_password.ClientID%>");
.
.
.
.
document.getElementById("<%=lbl_passwordStrength.ClientID%>").innerHTML = strength;
passwordTextbox.style.color = "white";
passwordTextbox.style.backgroundColor = backgroundColor;
Upvotes: 2