Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

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++;           
    } 
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top