Home > Mobile >  if stops checking true/false after first match
if stops checking true/false after first match

Time:01-06

I have a if statement where I want to run a function on three fields.

The problem is that the if stops checking the rest of the statement after the first hit, meaning that the rest of the fields that are empty wont get the css class which indicates a problem to the user.

This is the function that checks if the selected field is empty

function emptyCheck(field) {
    if(!field.val().trim()) {
      field.addClass("validation");
      return false;
    }else {
      field.removeClass("validation");
      return true;
    }
  }

This is where the checking function is run (part of a larger function)

if(type == "Book") {
  if(!emptyCheck($("#height")) ||
     !emptyCheck($("#width")) ||
     !emptyCheck($("#length"))) {
      return false;
      }else {
        if(!dimensionCheck()) {
          return false;
        }else {
          allGood = true;
        }
      }
    }

CodePudding user response:

You need to avoid the short-circuiting behavior, of one call's return false resulting in the subsequent calls not starting at all.

Call all emptyChecks first, putting the return values into an array, and then check that array for whether any of its values are false.

if (type == "Book") {
    const results = ['height', 'width', 'length'].map(str => emptyCheck($('#'   str)));
    if (results.includes(false)) {
        return false
    } else {
        // all are true - continue with desired logic
    }
  •  Tags:  
  • Related