Project V1
Project V1

Reputation: 357

Problem with jquery .submit() and variables

I am not sure what to do and why it is not working it is my first attempt at something like this.

Here is a fiddle of it http://jsfiddle.net/ProjectV1/LVPtN/

You will notice in javascript I have a var error which is by default false.

If there is an error it is true.

I have displayed the value of error next to each input on my form.

If the variable error is false it should submit the form and false it shouldn't.

The problem arises when an error occurs, and is then corrected the form will not submit.

Look at the fiddle. The form directs to google just for testing.

Upvotes: 2

Views: 173

Answers (1)

James Jithin
James Jithin

Reputation: 10565

I think, the issue is with the error being inside the function which will be called on blur. And when the function call is done, it goes undefined. The deal is that the variable should be global. You will need to put this above the $(document).ready() This should work:

var error = false;

$('#joinForm input').blur(function() {
    var id = $(this).attr('id');
    var val = $(this).val();
    if (id == 'email') {
        $('#emailMsg').hide();
        if (val == '') {
            error = true;
            $('#' + id).after('<div id="emailMsg" class="error">' + error + '</div>');
        }
        else {
            $('#' + id).after('<div id="emailMsg" class="success">' + error + '</div>');
        }
    }
    if (id == 'cemail') {
        $('#cemailMsg').hide();
    }
    if (id == 'password') {
        $('#passwordMsg').hide();
        if (val == '') {
            error = true;
            $('#' + id).after('<div id="passwordMsg" class="error">' + error + '</div>');
        }
        else {
            $('#' + id).after('<div id="passwordMsg" class="success">' + error + '</div>');
        }
    }
    if (id == 'cpassword') {
        $('#cpasswordMsg').hide();
    }
    if (id == 'username') {
        $('#usernameMsg').hide();
        if (val == '') {
            error = true;
            $('#' + id).after('<div id="usernameMsg" class="error">' + error + '</div>');
        }
        else {
            $('#' + id).after('<div id="usernameMsg" class="success">' + error + '</div>');
        }
    }
    $('#joinForm').submit(function(){
        if (error == true) {
            return false;
        }
        else {
            return true;
        }
    });
});

Upvotes: 1

Related Questions