我正在验证表单,我只能显示第一条错误消息:
ContactUs.prototype.desktopErrors = function(){
var THIS = this;
THIS.$el.find('#submit').on('click', function(){
if (!$('#firstName').val().length) {
$('.nameErrs li').text("We can't verify your name")
} else if (!$('#lastName').val().length) {
$('.nameErrs li').text("We can't verify your last name")
} else if (!$('#emailAddress').val().length) {
$('.emailErrs li').text("We can't verify your email address")
} else if (!$('#lastName').val().length) {
$('.emailErrs li').text("We can't verify the subject")
}
});
return THIS;
};
这是JADE:
.row
.form-group
label.first_name_label(for="firstName") First Name*
input.first_name_input(required type="text" class="form-control" id="firstName")
.form-group
label.last_name_label(for="lastName") Last Name*
input.last_name_input(required type="text" class="form-control" id="lastName")
ul.nameErrs
li.full
.row
.form-group
label.email_address_label(for="emailAddress") Email Address*
input.email_address_input(required type="email" class="form-control" id="emailAddress")
.form-group
label.(for="subject") Subject*
input.(required type="text" class="form-control" id="subject")
ul.emailErrs
li.full
因此,如果所有字段都为空,则我无法显示所有错误消息,只显示第一个。
建议?
答案 0 :(得分:3)
if else
是一个失败的快速逻辑构造
您只需要if blocks
使用所有字段
THIS.$el.find('#submit').on('click', function(){
if (!$('#firstName').val().length) {
$('.nameErrs li').text("We can't verify your name")
}
if (!$('#lastName').val().length) {
$('.nameErrs li').text("We can't verify your last name")
}
if (!$('#emailAddress').val().length) {
$('.emailErrs li').text("We can't verify your email address")
}
if (!$('#lastName').val().length) {
$('.emailErrs li').text("We can't verify the subject")
}
});
答案 1 :(得分:0)
断开else if
逻辑。然后附加文本以便不覆盖。
THIS.$el.find('#submit').on('click', function(){
$('.nameErrs li').text("");
$('.emailErrs li').text("");
if (!$('#firstName').val().length) {
$('.nameErrs li').text("We can't verify your name")
}
if (!$('#lastName').val().length) {
$('.nameErrs li').text( $('.nameErrs li').text() + "We can't verify your last name")
}
if (!$('#emailAddress').val().length) {
$('.emailErrs li').text("We can't verify your email address")
}
// FYI: in your snippet this is a reevaluation of lastname
if (!$('#subject').val().length) {
$('.emailErrs li').text( $('.emailErrs li').text() + "We can't verify the subject")
}
});