0

I know the title is a bad title, I don't know any way to explain this other than with an example:

$('form').submit(function(){
  $(this).find('input').each(function(){
    if($(this).hasClass('error'))
      return false;
  });
});

However, the "return false" is returning the ".each()" with false. How can I "pass" it onto the ".submit()"?

5 Answers 5

5

If you're looking for any input in that form that has the class error, you could do:

return $(this).find('input.error').length == 0;
Sign up to request clarification or add additional context in comments.

2 Comments

Meh, your version is easier to approach logically, mine has inversion, if there is a class that returns true so you would have to invert it to return false as he desires. +1 for a more straightforward approach. =P
@MatthewCox - Using hasClass would've been cleaner if it wasn't for the inversion. If jQuery had a boolean way to check if any element matched the selector, that would be the cleanest, like a shortcut for checking length. $(this).any('input.error').
2

Just simplify it. It appears that if you find one instance of this class you want to return false, which can be done like so:

$('form').submit(function()
{
    return $(this).find('input').hasClass('error') == false;
});

You could also use a NOT operator but that just looks ugly with selectors IMO.

Comments

1

Because the .each() method calls a callback function you can't return from the submit from inside the .each() callback. So, you have to set a variable for your return value and then return that later.

$('form').submit(function(){
  var retVal = true;
  $(this).find('input').each(function(){
    if($(this).hasClass('error'))
      retVal = false;
      return false;
  });
  return(retVal);
});

You could also solve this problem by letting the selector engine do your searching rather than iterating yourself with .each() like this:

$('form').submit(function(){
  if ($(this).find('input.error').length != 0) {
      return(false);
  }
});

or a little more succinctly:

$('form').submit(function(){
      return($(this).find('input.error').length == 0);
});

Comments

0

Declare a varaible outside the loop, and set before exiting the loop, then return the value of the variable:

$('form').submit(function(){
  var result = true;
  $(this).find('input').each(function(){
    if($(this).hasClass('error'))
      result = false;
      return false; // exit loop
  });
  return result;
});

Comments

0
$('form').submit(function(){
  var allok = true;
  $(this).find('input').each(function(){
    if($(this).hasClass('error'))
      allok  =false;
  });
  return allok;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.