kettlepot
kettlepot

Reputation: 11011

jQuery .submit() won't execute no matter what

I have a page which contains two forms, both with an unique ID. I need to make the page fade out when either of the forms is submitted. However, it won't work.

Here's the code

$(document).ready(function(){
        $('#container').fadeOut(0);
        $('#container').fadeIn(500);
    });

    $('form').submit(function(){
        alert("Hello.");
        $('#container').fadeOut(500);
    });

As you can see from the code, it should show an alert but it does not, and it doesn't even fade out the page. My forms contain a text input, which is set to readonly, and a submit button.

Thanks in advance.

Upvotes: 0

Views: 530

Answers (4)

Richard Dalton
Richard Dalton

Reputation: 35793

Try this:

$(document).ready(function(){
    $('#container').fadeOut(0);
    $('#container').fadeIn(500);

    $('form').submit(function(e){
        e.preventDefault();
        var form = this;
        $('#container').fadeOut(500, function() { 
            form.submit();
        });       
    });
});

The submit binding was outside of the document ready and it probably couldn't find the form tag when it was executed.

jsfiddle example - http://jsfiddle.net/KbaG3/

Upvotes: 1

Jepser Bernardino
Jepser Bernardino

Reputation: 1372

Try:

jQuery(function($){
    $('#container').hide().fadeIn(500);

    $('form').submit(function(){
        alert("Hello.");
        $('#container').fadeOut(500);
    });
});

I think is a cleaner code and and also no conflict proof.

Upvotes: 0

JohnP
JohnP

Reputation: 50039

Unless you're including this JS at the bottom of the page, you should move the $(form).... code inside the $(document).ready() block

$(document).ready(function(){
        $('#container').fadeOut(0);
        $('#container').fadeIn(500);


    $('form').submit(function(){
        alert("Hello.");
        $('#container').fadeOut(500);
    });
});

This is because your element doesn't exist when you are binding the event to it

Upvotes: 0

Dan Breen
Dan Breen

Reputation: 12934

You should probably move the submit event register function to inside the document ready function so that you can be sure the DOM is ready before registering the function.

If that doesn't help, see if there are any javascript errors being thrown on the page which might halt the execution.

Upvotes: 0

Related Questions