David Geismar David Geismar - 4 months ago 8
jQuery Question

JS function with jquery always return undefined

I am building a Js function with Jquery checking if certain inputs are empty or not for validation. Here's the function that checks if the inputs are empty or not:

function isValid(elements){
var validation = false
elements.each(function() {
if ($( this ).val().length > 0){
validation = true
}
else {
validation
}
});
validation
}


however whatever I do my function returns undefined and never the boolean value that is supposed to be contained in the validation variable ?

What should I do for my function to return true or false ?

Answer

You can return false if at least one element is empty, otherwise return true.

function isValid(elements){
  var validation = true;

  elements.each(function() {
    if ($( this ).val().trim().length === 0){
      validation = false;
    }
  });

  return validation;
}