Reputation: 1569
I'm trying to setup some jQuery to validate an array of fields for a form. I feel like I'm on the right track but the setup doesn't work as I want it to. Currently, if any of the fields in the array have been filled in, the else statement is triggered. But I want to make sure ALL fields in the array are filled in. I'm wondering if I need to create a boolean variable?
(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));
Upvotes: 0
Views: 49
Reputation: 1913
I think you want to do something like this:
(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));
Upvotes: 1