我有这个javascript工作得很好 -
var employeename = $("#employeename");
var employeenameInfo = $("#employeenameInfo");
employeename.blur(validateEmployeename);
function validateEmployeename(){
//if it's NOT valid
if(employeename.val().length < 4){
employeename.addClass("error");
employeenameInfo.text("We want names with more than 3 letters!");
employeenameInfo.addClass("error");
return false;
}
//if it's valid
else{
employeename.removeClass("error");
employeenameInfo.text("Full Name.");
employeenameInfo.removeClass("error");
return true;
}
}
然而,我没有为所有不同的字段提供这个函数的大列表,而是想传递一个字段。
function validateGeneric(field){
然而,无论我尝试什么只是给我错误,我真的卡住了。任何帮助赞赏。这也带来了info字段的另一个问题,我可以存储原始文本并只恢复它而不是新字符串吗?
答案 0 :(得分:0)
您可以使用$(this)获取触发事件的字段。你也应该把信息字段作为兄弟信息类
$('input.to_be_validated').blur(validateInput);
function validateInput(e){
var input = $(this)
var info = input.parent.find('.info')
//if it's NOT valid
if(input.val().length < 4){
input.addClass("error");
info.text("We want names with more than 3 letters!");
info.addClass("error");
return false;
}
//if it's valid
else{
input.removeClass("error");
info.text("Full Name.");
info.removeClass("error");
return true;
}
}
编辑:忘记了信息字段
答案 1 :(得分:0)
您需要做的就是引用您传递给函数的field
var,因此您的代码变为:
function validateEmployeename(field, fieldinfo){
//if it's NOT valid
if(field.val().length < 4){
field.addClass("error");
fieldinfo.text("We want names with more than 3 letters!");
fieldinfo.addClass("error");
return false;
}
//if it's valid
else{
field.removeClass("error");
fieldinfo.text("Full Name.");
fieldinfo.removeClass("error");
return true;
}
}
答案 2 :(得分:0)
您也可以使用多个选择器:
$("input[name='employeename'], input[name='employeename2']").blur(function() {
// put your validation routine for fields that should contain names
$(this).next("#employeenameInfo").html("info here"); // note that you don't have unique id here, better to find element you want to put your error message by tagname/class, like "span.error"
});
$("input[name='employeemail'], input[name='employeemail2']").blur(function() {
// put your validation routine for fields that should contain email addresses
$(this).next("#emailInfo").html("info here"); // note that you don't have unique id here, better to find element you want to put your error message by tagname/class, like "span.error"
});
这样您就不需要将任何内容传递给验证函数,所有内容都将在$(this)
左右解决,前提是您有适当的元素来填充附近的错误消息:
<input type="text" name="employeename" />
<span class="error" />