0

I'm trying to learn how to validate a form and I have this problem:

When I run this code and I don't enter anything - the form should not send, but it does. My question is ... Why, and how can I fix it?

the html:

<form method="post" action="#">
<fieldset>
<legend>Formular</legend>
<label for="name">Name: </label>
<input type="text" class="required" name="name" value="" />
<br /><br />
<label for="pass">Password: </label>
<input type="password" class="required" name="pass" value="" />
<br /><br />
<input type="submit" value="Submit!" />
</fieldset>
</form>

the jQuery:

$('#obal form').submit(function() { 
    $('.required').each(function() {
        if($(this).val() == "") {                   
            if (errorCount === undefined) {
                    var errorCount = 1;
            } else {
                ++errorCount;
            } 
        } 
    }); 

    if (errorCount > 0) {
        window.alert( 'You didnt pass' );
        return false;
    } else {
        return true;
    }   
});

If you know any other improvements the code could take, you can tell me aswell, thanks .. :-)

2
  • Is the form a child of an element with the ID of obal? If not, the selector you use wouldn't select the form. Commented Jul 22, 2009 at 21:56
  • Yes, it is. Also tryed Inke's code, but still doesn't work. My guess is, that there is something wrong with the 'errorCount' variable, because it doesn't get into the - if(errorCount > 0) { } Commented Jul 22, 2009 at 22:03

4 Answers 4

3

Your current code is not working because errorCount is local to the anonymous function passed to the each method. It won't be visible outside.

This means when you do errorCount > 0 after your each method, it evaluates to false and submits the form.

I would write it your function like this,

$('#obal form').submit(
    function(ev) 
    { 
        var errorCount = 0; //define your errorCount variable to zero before you 
                            //iterate using each, errorCount will be available inside your each iteration function.
        $('.required').each(
            function() 
            {
                //Due to JavaScript clousures, you can access errorCount in this function.
                if($(this).val() === '')
                    errorCount++;  
            }
        );

        //If we don't find any errors, we return. This will let the browser continue submitting the form.      
        if(errorCount == 0)
            return;

        //If control comes here, it means there were errors. Prevent form submission and display error message.
        ev.preventDefault();
        alert('Validation failure.');
    }
);

EDIT:

Why your code doesn't work?

Let's give name to the anonymous function (say myEachLoop) passed to the '.each' method.

$('#obal form').submit(function() { 
$('.required').each(

  function myEachLoop () 
  {
    if($(this).val() == "") {                               
        if (errorCount === undefined) {
                var errorCount = 1; //you have defined the errorCount which is 'local' to the 'myEachLoop' function. Once myEachLoop function is over. errorCount variable is gone! 

        } else {
            ++errorCount;
        } 
    } 
}); 

//errorCount is 'undefined' here because the previously defined errorCount variable is gone.
if (errorCount > 0) {
    window.alert( 'You didnt pass' );
    return false;
} else {
    return true;
}   
});

Do you now see the mistake in your code?

You also need to understand JavaScript closures to know why my code is working.

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

3 Comments

@Mike, I hope you understood where the actual problem was. As I edited my answer to add comment about how you used errorCount variable incorrectly which was causing your code to fail.
@Yogi, Well, I see what you did there, but I can't say I'm 100% sure why it was not possible the way I did it.
Get it now! Thanks so much again.
3

Change this:

$('#obal form').submit(function() {

to this:

$('#obal form').submit(function(event) {
    event.preventDefault();

and if your form is valid, do this (within your .submit function):

$(this).submit();

and your form will be submitted.

1 Comment

@Mike - what doesn't work, try to be more specific and you'll get better assistance.
0

You may want to try this jQuery plugin. It's extremely flexible and easy to use.

1 Comment

When I really need it, I will. I was just hoping I could learn to do it myself. :-)
0

I would declare error count before the loop to make sure the scope is correct:

var errorCount = 0;
$('.required').each(function() {
    if($(this).val() == "") {                               
        errorCount++;           
    } 
});

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.