Blog

Using .submit(), return false, and .serialize() with Forms
Posted on June 9, 2015 in jQuery by Matt Jennings

Example code below of what .submit(), return false, and .serialize() in jQuery do when used with forms:

<!DOCTYPE html>
<html>
<head>

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

    <script type="text/javascript">

    $(function(){

        // Definition of .submit():
        // .submit() binds an event handler to the
        // "submit" JavaScript event, or triggers
        // that event on an element.

        // .submit() handler gets attached to a form
        $("form").submit(function() {

            // Definition of .serialize():
            // Encode a set of form elements as a string for submission.

            // Example output for a FORM submission
            // using .serialize():
            // first_name=Jane&last_name=Doe&email=jane%40example.com
            console.log($(this).serialize());

            // return false; below stops page from
            // executing post.php and refreshing
            return false;

        });

        // Triggers a submit event on the form when I
        // click the element with a .btn class
        $(".btn").click(function() {
            $("form").submit();
        });

    });

    </script>

</head>
<body>

    <form action="post.php" method="post">

        First Name <input name="first_name" type="text" /><br /><br />
        Last Name <input name="last_name" type="text" /><br /><br />
        Email <input name="email" type="text" /><br /><br />
        <input value="submit!" type="submit" />

    </form>

    <button class="btn">Click me to use .submit() differently!</button>

</body>
</html>

Leave a Reply