0

I have a form attribute like so:

onsubmit="return valMyForm(this);"

And a jQuery function like so:

function valMyForm(f) {
  $(f,"input").each(function() {
      if($(this).length < 1) {
          alert("All Fields Required.");
          return false;
      }
          else
          return false;
  });
}

The form still submits even if I remove all of the code and just put return false;

2
  • Not to nit-pick, but the last else isn't necessary. ;-) Commented Feb 12, 2011 at 19:05
  • @Brad, thank you, I am always looking for shorter ways to write code. Commented Feb 12, 2011 at 19:05

2 Answers 2

3

The return false inside the each function is just exiting out of the each loop. It's not returning the value for valMyForm

You should use something like a valid variable and return that:

function valMyForm(f) {
  var valid = true;
  $("input", f).each(function() {
      if($(this).val().length < 1) {
          alert("All Fields Required.");
          valid = false;
      }
  });

  return valid;
}

Here is a working example for you: http://jsfiddle.net/adpMT/

Sign up to request clarification or add additional context in comments.

3 Comments

here's a demo of what I've come up with: jsfiddle.net/Unny3/1 in case you're interested.
@Brad Christie - Ah, I actually just posted a fiddle for you in my answer
I think you're is best answer. I can't seem to get short-hand of [value=""] wot work from Darin's example. So +1 to you. ;-)
1

When you return you are inside the .each function so you are not actually returning anything from the valMyForm method.

I would recommend you avoid mixing markup with javascript and do this unobtrusively:

<form action="/foo" id="myform">
   ... some input fields
</form>

and then:

$(function() {
    $('#myform').submit(function() {
        // see if the form contains some empty inputs
        return $(this).find(':input[value=""]').length > 0;
    });
});

10 Comments

@Darin: I may be wrong, and don't know how the function is being called, but I think the input selector needs to be reversed too, to: $('input',f). But again, I don't know how the function's being called.
@Darin Dimitrov, ha it would help if I told it to check the length of the value.
@Brad, the form is passing my function a parameter of 'this'.
@nick: Brad is right. Your selector is looking for f within the context of all the input elements on the page. You should be looking for input elements in the context of f. $('input',f) or better $(f).find('input')
@Brad: Yep, I know. That's why $(f).find('input') is better. It doesn't need to run through a bunch of tests before it just flips it around and starts over. :o)
|

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.