Submitting a form with jQuery

We know that submit buttons are used in HTML forms to submit data to a server. Apart from submit buttons, JavaScript also provides a submit method that can be used to submit forms.

In this recipe, you will learn how to submit forms the jQuery way and will also learn how the form submission can be controlled using the submit button.

Getting ready

Get the jQuery library to use with this recipe.

How to do it...

  1. Create a new file, name it as formSubmit.html and save it in the chapter1 directory.
  2. Write the following code, which creates a form with an input button (not submit button). Add some jQuery code that will be triggered on clicking the button and will submit the form.
    <html>
      <head>
        <title>Submitting forms</title>
      </head>
      <body>
        <form id="myForm">
          <input type="button" value="Submit Form" />
        </form>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
          $(document).ready(function ()
          {
            $('input:button').click(function()
            {
              $('#myForm').submit();
            });
          });
        </script>
      </body>
    </html>
  3. Run the formSubmit.html file and click on the input button. It will submit the form.

How it works...

In this example we attached the click event handler to the input button. The event handler function will execute when the button is clicked. On clicking the button, jQuery's submit() method is called on the form, which submits the form. All browsers have a native submit method to submit the form programmatically. jQuery has wrapped this functionality into its own submit() method.

There's more...

Controlling form submission

If a form has a submit button then we can control whether to submit the form or not. In this case we will have to attach an event handler to the form. This event handler will be executed when a submit button on that particular form is clicked.

$('#myForm').submit(function()
{
  return false;
});

The above code will execute when a submit button on the form with ID myForm is clicked. If false is returned by the handler function, the form will not be submitted. This can be pretty handy for validating forms. The code for validating form values can be placed in the handler function. If values are validated, true can be returned, which will submit the form. In case the validation fails, false can be returned, which will not allow the form to be submitted.

Another option is to use preventDefault(). As the name indicates, preventDefault() prevents the default event from being executed. It is a property of the event object.

$('#myForm').submit(function(event)
{
  event.preventDefault()
});

See also

  • Binding and unbinding elements explains how to add and remove events from elements.