我有这个 html 表单代码:
$("#email").blur(function(){
//check to two here.
if ($("#email").val() != $("#email_repeat").val())
{
$("#email_repeat").keyup(function(){
if ($("#email").val() != $("#email_repeat").val()) {
// emails don't match
}
});
}
});
<label for="email">Email address:</label>
<input type="email" id="email" name="email" placeholder="em@i.l"
title="Enter email address" required>
<label for="email_repeat">Confirm email address:</label>
<input type="email" id="email_repeat" name="email_repeat" placeholder="em@i.l"
title="Confirm email address" required >
我想确保它们实时匹配,并且我知道我需要使用 on key up 事件。
我在这里错过了什么?
最佳答案
您每次检查时都在定义一个 keyup 事件。这是绝对错误和不合逻辑的。
就像你说的:
If user leaves focus on 'email' textbox and emails don't match 'email_repeat' then add an event to 'email_repeat' so if keyup occurs, if email don't match...
应该这样做:
$("#email").on('keyup', ValidateEmails); // Remove these two if you don't want it to be
$("#email_repeat").on('keyup', ValidateEmails); // validated after user clicks a key
$("#email").blur(ValidateEmails); // Remove these two if you don't want it to be
$("#email_repeat").blur(ValidateEmails); // validated when a user loses focus
function ValidateEmails()
{
if ($("#email").val() != $("#email_repeat").val())
{
// emails dont match
}
}
我是这么说的:
If user leaves the focus or clicks a key on either 'email' or 'email_repeat' textboxes then check if emails are not equal
关于javascript - 使用 onkeyup 事件确保电子邮件匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30795549/