如何在两个密码框均为空时隐藏密码匹配提示信息
Fixing the Lingering Password Match Message Issue
Hey there! I see the problem—your current code only checks if the passwords match or not, but it doesn’t handle the case where both password fields are emptied. Let’s adjust the JavaScript to fix that right away.
Modified JavaScript Code
function isPasswordMatch() { var password = $("#txtNewPassword").val(); var confirmPassword = $("#txtConfirmPassword").val(); // First check if both fields are completely empty if (password.trim() === "" && confirmPassword.trim() === "") { $("#divCheckPassword").html(""); } else if (password !== confirmPassword) { $("#divCheckPassword").html("Passwords do not match!"); } else { $("#divCheckPassword").html("Passwords match."); } } $(document).ready(function () { $("#txtConfirmPassword").keyup(isPasswordMatch); // Optional: Bind the event to the new password field too for real-time updates $("#txtNewPassword").keyup(isPasswordMatch); });
Key Changes Explained
- Added a priority check: If both input fields are empty (after trimming any accidental whitespace), we clear the content of
#divCheckPasswordto hide the message entirely. - I also added an optional binding to the
#txtNewPasswordfield’s keyup event—this way, if you type in the first password field after matching and emptying, the message updates immediately instead of only when you interact with the confirm field.
Small Cleanup Tip
You can remove the onChange="isPasswordMatch();" attribute from your confirm password input in the HTML. Since we’re already binding the keyup event via jQuery, this avoids duplicate function calls and keeps your event handling more organized.
内容的提问来源于stack exchange,提问作者FIFA oneterahertz
相关产品推荐
相关产品推荐

