我有这个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事件。
我在这里缺少什么?
答案 0 :(得分:3)
每次检查时都要定义一个keyup事件。这是绝对错误和不合逻辑的。
就像你说的那样:
如果用户将注意力集中在“电子邮件”文本框上,并且电子邮件不匹配 'email_repeat'然后将事件添加到'email_repeat',以便在发生密钥时,如果 电子邮件不匹配...
这是应该做的:
$("#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
}
}
我就这么说:
如果用户离开焦点或点击“电子邮件”或 'email_repeat'文本框然后检查电子邮件是否不相等