Chris
Chris

Reputation: 8442

Form refreshes constantly with $.submit()

Something is eluding me here. Every time I press the submit button, the form just refreshes the page and I never get the "Form Submitted" message. I don't want the form to refresh the page.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Test</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
        <script type="text/javascript">

            (function($){

                $("#my-form").submit(function(e){
                    e.preventDefault();
                    alert("Form Submitted");
                });

            })(jQuery);

        </script>
    </head>
    <body>

        <form id="my-form" method="post" action="">

            <input type="text" placeholder="Input something..." />
            <input type="submit" value="Submit" />

        </form>

    </body>
</html>

Upvotes: 1

Views: 125

Answers (1)

alex
alex

Reputation: 490471

You need to wrap your code with a DOM ready event.

$(function() {
   ...
});

Your code as now tries to bind the event when the element isn't ready in the DOM, therefore the event is never attached.

Upvotes: 2

Related Questions