views:

1075

answers:

4

Hello, 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 .. :-)

+3  A: 

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.

inkedmn
Tryed it, still doesn't work :-/
Mike
@Mike - what doesn't work, try to be more specific and you'll get better assistance.
karim79
A: 

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

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

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++;           
    } 
});
John Sheehan
+1  A: 

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.

SolutionYogi
Works fine, thank's so much. :)
Mike
@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.
SolutionYogi
@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.
Mike
Get it now! Thanks so much again.
Mike