Passing a variable from a function to an if statement

Viewed 2126

I have a submit button on a form for which I assigned a function to check required and visible fields. Upon encountering an empty field its supposed to add a class to a field, as well as display and error message. I have this jquery script:

$(".submitBtn").click(function(validateAll) {
  if (validated = false) {
    alert("!!!");
    displayValidationErr();
  } else {
    $('#questionBody').submit();
  }
});

function validateAll() {
  var validated = true;
  $('.form-control').filter('[required]:visible').each(function() {
    if ($(this).val() === '') {
      $(this).addClass("emptyRequired");
      validated = false;
    }
  });
}

function displayValidationErr() {
  $("#validationError").fadeTo(2000, 600).slideUp(600, function() {
    $("#validationError").slideUp(600);
  });
}

I am unable to pass a variable from "validateAll" function further upon clicking a button. Function works fine by itself, but not with if\else. I am very new to this stuff, so please be easy on me. :)

Thank you!

7 Answers

You can't pass any parameters to the event handler functions. That being said, you don't need to in this case. Your validated variable is also only defined within validateAll(), so is not accessible from the click handler.

To fix the issue you can make validateAll() return the boolean value to indicate if the form is valid, then deal with that response in the click event handler after calling the validateAll() function directly. Try this:

$(".submitBtn").click(function() {
  if (!validateAll()) {
    alert("!!!");
    displayValidationErr();
  } else {
    $('#questionBody').submit();
  }
});

function validateAll() {
  var validated = true;
  $('.form-control').filter('[required]:visible').each(function() {
    if ($(this).val() === '') {
      $(this).addClass("emptyRequired");
      validated = false;
    }
  });
  return validated;
}

One final note to be aware of, = is used to set a value while == or === is used to compare values. Your original if statement wouldn't have worked as you expect because you're using =.

Inside your validateAll function you are defining validated which creates a function scope that is limited to that function. You can either create a global variable or just give a return value.

Global variable approach:

var validated = true; // in the same scope as your two functions

$( ".submitBtn" ).click(function(){
  validated = true;
  validateAll();

  if (validated == false){ // make sure double "=" is set
    alert("!!!");
    displayValidationErr();         
  } 
  else {
    $('#questionBody').submit();
  }
});

function validateAll() {
  // var validated = true;
  $('.form-control').filter('[required]:visible').each(function() {
    if ( $(this).val() === '' ) {
      $(this).addClass("emptyRequired");
      validated = false;
    }
  });
}

Return approach:

$( ".submitBtn" ).click(function(){
  validated = validateAll();

  if (validated == false){
    alert("!!!");
    displayValidationErr();         
  } 
  else {
    $('#questionBody').submit();
  }
});

function validateAll() {
  var validated = true;
  $('.form-control').filter('[required]:visible').each(function() {
    if ( $(this).val() === '' ) {
      $(this).addClass("emptyRequired");
      validated = false;
    }
  });

  return validated;
}

Also, a small tipp for a little bit more easily readable code: people tend to be more happy with positive-first if blocks, so instead of beginning with a double negative if condition like so:

if (validated == false){
  alert("!!!");
  displayValidationErr();         
} 
else {
  $('#questionBody').submit();
}

its best practice to start off with whats expected/ wanted behaviour:

if (validated) {
  $('#questionBody').submit();
} 
else {
  alert("!!!");
  displayValidationErr();         
}

your function scope is different as in java script the variables are hoisted. you can call your validateAll() function which will return the flag explicitly in your submitbtn function

You have a "scope issue": your validated variable is only available in validateAll().

You can either make it "global" (not recommended) or return it from validateAll() then make the call explicitly at the top of submitBtn click and check the result.

$(".submitBtn").click(function() {    
  // call validateAll() and check the result  
  if (validateAll() == false) {
    alert("!!!");
    displayValidationErr();
  } else {
    $('#questionBody').submit();
  }
});

function validateAll() {
  var validated = true;
  $('.form-control').filter('[required]:visible').each(function() {
    if ($(this).val() === '') {
      $(this).addClass("emptyRequired");
      validated = false;
    }
  });
  
  // return the result
  return validated;
}

function displayValidationErr() {
  $("#validationError").fadeTo(2000, 600).slideUp(600, function() {
    $("#validationError").slideUp(600);
  });
}

$(document).ready(function(){
var validated;
$( ".submitBtn" ).click(function(){
   validated = true;
   validateAll();
   if(!validated){
     alert("!!!");
     displayValidationErr();         
   } else {
     $('#questionBody').submit();
   }
});

function validateAll() {
  $('.form-control').filter('[required]:visible').each(function() {
    if ( $(this).val() === '' ) {
        $(this).addClass("emptyRequired");
        validated = false;
    }
  });

}

function displayValidationErr() {
  $("#validationError").fadeTo(2000, 600).slideUp(600, function(){
  $("#validationError").slideUp(600);
});
}

You can try this code. On button click, you can make the validation flag true, then call your function to check if fields are not empty and if its an empty field the flag will return false. I have not tested this code but it should work!!

Following code should fix your problem, you need to get the boolean vaidation from function and store it.

$(".submitBtn").click(function() {
  var validated = validateAll()
  if (validated == false) {
    alert("!!!");
    displayValidationErr();
  } else {
    $('#questionBody').submit();
  }
});

function validateAll() {
  var validated = true;
  $('.form-control').filter('[required]:visible').each(function() {
    if ($(this).val() === '') {
      $(this).addClass("emptyRequired");
      validated = false;
    }
  });
  return validated;
}

Try adding (function($){//yoursnippet})(jQuery); around the code, like so:

(function($){
$( ".submitBtn" ).click(function(validateAll){
   if(validated = false){
  alert("!!!");
     displayValidationErr();         
   } else {
     $('#questionBody').submit();
   }
});

function validateAll() {
 var validated = true;
  $('.form-control').filter('[required]:visible').each(function() {
    if ( $(this).val() === '' ) {
        $(this).addClass("emptyRequired");
  validated = false;
 }
  });
  
}

function displayValidationErr() {
  $("#validationError").fadeTo(2000, 600).slideUp(600, function(){
  $("#validationError").slideUp(600);
});

}
})(jQuery);

Related