Axel A. García
Axel A. García

Reputation: 683

Javascript onSubmit function auto executing

I got a problem with my validation code... I got a form with two fields (user, pass) and a jQuery function that executes a function on submit:

jQuery(document).ready(function($) {
    $('#login-form').on('submit', validateData());

    function validateData() {
        userInput = $('#in-user');
        userCntrl = userInput.closest('.control-group');
        passInput = $('#in-pass');
        passCntrl = passInput.closest('.control-group');

        userCntrl.addClass('error'); // This executes on page load, not on submit

        formSubmit = false;

        console.log( userInput.val() ); // This logs on page load, not on submit

        return formSubmit;
    }
});

The fact is that this code runs on page load but onSubmit nothing happens...

I'm sure this is an easy one, but I can't see a solution.

Upvotes: 2

Views: 741

Answers (2)

RichieHindle
RichieHindle

Reputation: 281495

You need:

$('#login-form').on('submit', validateData);

Note the lack of parentheses after validateData.

As you have it, you're calling the function on page load and setting its return value (false) as the submit handler for your form.

(And you should do that after defining the validateData function.)

Upvotes: 6

A. Wolff
A. Wolff

Reputation: 74420

Should be:

$('#login-form').on('submit', validateData);

Upvotes: 3

Related Questions