Reputation: 221
I am trying to clean up this spaghettified code and I decided to separate the methods into separate functional objects and then call them within a single validate function. The code runs correctly on the first function and returns an alert box correctly. However, when I fix the first alert and resubmit the form the second function fires an alert at me to fix something, I click okay and immediately get an alert on the third function. Obviously I need to put in some code to stop the program from running after I click okay to the second functions alert so I can fix the issue, but how?
var checkboxes = document.getElementsByName('days');
var valid = false;
function textFieldValid(){
var textFieldsReq = document.getElementsByName('textFieldReq');
for( var i=0;i<9;i++ ){
if ( !textFieldsReq[i].value ){
alert ( 'You need to fill in the required* text field!' );
textFieldsReq[i].focus();
return false;
}
}
};
function checkboxesValid(){
for ( var i = 0;i<checkboxes.length;i++ ){
if ( checkboxes[i].checked ) {
valid = true;
break;
}
}
if ( !valid ) {
alert( 'You need to select at least one day!' );
checkboxes[0].focus();
return false;
}
}
function lodgeValid(){
var lodging = document.getElementsByName('lodge');
for( var i=0; i<lodging.length; i++ ){
if( lodging[i].checked ){
valid=true;
break;
}
}
if ( !valid ) {
alert( 'You need to select at least one option!' );
lodging[0].focus();
return false;
}
}
function validate(textFieldsReq){
textFieldValid();
checkboxesValid();
lodgeValid();
};
Upvotes: 0
Views: 64
Reputation: 388316
You need to return true/false from each of the tests and then
var checkboxes = document.getElementsByName('days');
function textFieldValid() {
var textFieldsReq = document.getElementsByName('textFieldReq');
for (var i = 0; i < 9; i++) {
if (!textFieldsReq[i].value) {
alert('You need to fill in the required* text field!');
textFieldsReq[i].focus();
return false;
}
}
//if valid return true
return true;
};
function checkboxesValid() {
//create local variables
var valid = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
valid = true;
break;
}
}
if (!valid) {
alert('You need to select at least one day!');
checkboxes[0].focus();
return false;
}
//if valid return true
return valid;
}
function lodgeValid() {
var lodging = document.getElementsByName('lodge'),
valid = false;
for (var i = 0; i < lodging.length; i++) {
if (lodging[i].checked) {
valid = true;
break;
}
}
if (!valid) {
alert('You need to select at least one option!');
lodging[0].focus();
return false;
}
//if valid return true
return valid;
}
function validate(textFieldsReq) {
//check whether all the tests are turnig true
return textFieldValid() && checkboxesValid() && lodgeValid();
};
Upvotes: 2