我正在尝试设置一些jQuery来验证表单的字段数组。我觉得我在正确的轨道上,但设置并不像我想要的那样有效。目前,如果已填充数组中的任何字段,则会触发else语句。但是我想确保填充数组中的所有字段。我想知道是否需要创建一个布尔变量?
(function($) {
$(document).ready(function() {
var SubmitBtn = $('#Schedule-Button');
var SchFirstName = $('#FName');
var SchLastName = $('#LName');
var SchAddress = $('#Address');
var SchCity = $('#City');
var SchZip = $('#Zip');
var SchEmail = $('#Email');
var SchPhone = $('#Phone');
var SchService = $('#ServiceReq');
var ApptForm = $('#appt-form');
var errors = false;
var SchedulePopup = $('[data-remodal-id=sch-modal]').remodal();
SubmitBtn.on('click', function(e){
var required = [SchFirstName, SchLastName, SchAddress, SchCity, SchZip, SchEmail, SchPhone, SchService];
e.preventDefault();
for(i=0;i<required.length;i++){
var input = required[i];
if((input.val()== "")){
input.addClass('error-field');
$('.Sch-Error-Msg').show();
}
else{
SchedulePopup.close();
input.removeClass('error-field');
$('.Sch-Error-Msg').hide();
}
}
});
});
}(jQuery));
答案 0 :(得分:1)
我想你想做这样的事情:
(function($) {
$(document).ready(function() {
var SubmitBtn = $('#Schedule-Button');
var SchFirstName = $('#FName');
var SchLastName = $('#LName');
var SchAddress = $('#Address');
var SchCity = $('#City');
var SchZip = $('#Zip');
var SchEmail = $('#Email');
var SchPhone = $('#Phone');
var SchService = $('#ServiceReq');
var ApptForm = $('#appt-form');
var errors = false;
var SchedulePopup = $('[data-remodal-id=sch-modal]').remodal();
SubmitBtn.on('click', function(e){
var required = [SchFirstName, SchLastName, SchAddress, SchCity, SchZip, SchEmail, SchPhone, SchService],
containsError = false;
e.preventDefault();
for(i=0;i<required.length;i++){
var input = required[i];
if((input.val()== "")){
containsError = true;
input.addClass('error-field');
$('.Sch-Error-Msg').show();
}
else{
input.removeClass('error-field');
$('.Sch-Error-Msg').hide();
}
}
if (containsError) {
SchedulePopup.close();
}
});
});
}(jQuery));