我有一个带有关于配置文件的标签的表单,在about部分我有textareas,我必须在其上执行验证。如何验证保存按钮单击,我不想验证每个textarea像下面的代码
$(document).ready(function(){ $(“#btnSaveMyChanges”)。click(function(){
var valid = true;
if ($("#txtAboutMySelf").val() == "") {
$("#ErrorAboutMySelf").html("This Field is Required.");
valid = false;
}
if ($("#txtAboutMyMatch").val() == "") {
$("#ErrorAboutMyMatch").html("This Field is Required.");
valid = false;
}
if ($("#txtWhatIamDoing").val() == "") {
$("#errmsg").html("invalide");
valid = false;
}
if ($("#txtIamReallyGood").val() == "") {
$("#errmsg").html("invalide");
valid = false;
}
if ($("#txtTheSixThings").val() == "") {
$("#errmsg").html("invalide");
valid = false;
}
if ($("#txtISpendaLot").val() == "") {
$("#errmsg").html("invalide");
valid = false;
}
if ($("#txtTheFirstThings").val() == "") {
$("#errmsg").html("invalide");
valid = false;
}
if ($("#txtOnaTypicalFriday").val() == "") {
$("#errmsg").html("invalide");
valid = false;
}
if ($("#txtMyFriendsDescribe").val() == "") {
$("#errmsg").html("invalide");
valid = false;
}
return valid;
});
});
创建一个函数然后在保存点击迭代表单获取所有文本区域,然后执行必要的字段验证,并且在keyup事件上我需要每个文本区域的maxlength为500
答案 0 :(得分:1)
尝试这样的事情:
var valid = true;
jQuery("#errmsg").html(""); //clear error messages first
jQuery("textarea").each(function() {
if(jQuery(this).val() == "") {
var errorText = "invalide";
var id = jQuery(this).attr("id");
if(id == "txtAboutMySelf" || id == "txtAboutMyMatch") {
errorText = "This Field is Required.";
}
var $errMsg = jQuery("#errmsg");
$errMsg.html($errMsg.html() + "<br />" + errorText); //you can't tell which error message belongs to what though; the same problem exists in your original solution.
valid = false;
}
});
您需要找到一种为错误消息提供上下文的方法。也就是说,您需要将错误消息与元素配对。您可以通过在每个元素旁边创建一个错误消息div或span,然后在出错时填充它来完成此操作。
答案 1 :(得分:0)
我相信你可以这样做:
$(document).ready(function () {
$("#btnSaveMyChanges").click(function () {
var valid = true;
if ($("#txtAboutMySelf").val() == "") {
$("#ErrorAboutMySelf").html("This Field is Required.");
valid = false;
}
if ($("#txtAboutMyMatch").val() == "") {
$("#ErrorAboutMyMatch").html("This Field is Required.");
valid = false;
}
if ($("#txtWhatIamDoing, #txtIamReallyGood, #txtTheSixThings, #txtISpendaLot, #txtTheFirstThings, #txtOnaTypicalFriday, #txtMyFriendsDescribe").val() == "") {
$("#errmsg").html("invalide");
valid = false;
return valid;
});
});
答案 2 :(得分:0)
Try this code
var clientdesc = $("textarea[name='client_desc[]']");
for(i = 0; i < clientdesc.length; i++){
if(clientdesc[i].value.trim() == ""){
document.getElementById('errormsg').innerHTML = 'error msg';
clientdesc[i].focus();
return false;
}
}
<textarea class="form-control" style="margin-bottom: 20px;" id="client_desc" name="client_desc[]" > </textarea>
<textarea class="form-control" style="margin-bottom: 20px;" id="client_desc" name="client_desc[]" > </textarea>