gpt4 book ai didi

javascript - 表单验证仅显示第一条错误消息

转载 作者:行者123 更新时间:2023-11-28 18:14:10 24 4
gpt4 key购买 nike

我正在验证表单,但只能显示第一条错误消息:

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;
};

这是杰德:

    .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

因此,如果所有字段均为空,则我无法显示所有错误消息,只能显示第一个错误消息。

建议?

最佳答案

if else 是一个快速失败的逻辑结构

您只需对所有字段使用 if block

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")
}
});

关于javascript - 表单验证仅显示第一条错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41028519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com