我的表格看起来像这样
<form id="new_user" action="users">
<input id="user_email" class="string email required span5 valid" type="text"
value="nicolas@demoreau.be" size="80" placeholder="user@domain.com" name="user[email]">
</form>
如果我想更新我的用户,表单ID将变为“edit_user”。我想仅在表单id包含“new”时才在我的user_email上添加规则。我试着这样做:
$("form[id*=new][data-validate=true]").find("#user_email").rules("add", {
remote: {
url: "check_email",
type: "post"
},
messages: {
remote: "There is already a user with this email address!"
}
});
但是当我使用编辑表单时会产生错误:“元素未定义”,这是正常的,因为它无法在任何地方找到user_email。
这样做的正确方法是什么?
答案 0 :(得分:0)
只尝试这个,
$("#user_email").rules("add", {
remote: {
url: "check_email",
type: "post"
},
messages: {
remote: "There is already a user with this email address!"
}
});
});
答案 1 :(得分:0)
在创建规则之前,检查您想要的表单和元素是否存在。
if ($("form[id*=new][data-validate=true]").find("#user_email").length > 0){
$('#user_email').rules("add", {
remote: {
url: "check_email",
type: "post"
},
messages: {
remote: "There is already a user with this email address!"
}
});
}