jQuery · Forms & AJAX

Form Handling

Forms are where users give you data. jQuery helps you intercept the submit, read every field — including checkboxes and dropdowns — and send it somewhere.

Intermediate 5 min Lesson 11 of 22 Runnable examplesExamples use jQuery 3.x.
Before you start:Events
0/22 in jQuery
On this page · 5 min · Intermediate

Learning objectives#

  • Handle the submit event and prevent page reloads
  • Read text, select, radio and checkbox values
  • Collect a whole form with serialize() and serializeArray()
  • Reset and disable forms during submission

Explanation#

Listen to the form’s submit event, not the button’s click: it also fires when the user presses Enter. Call e.preventDefault() if JavaScript handles the submission.

Text, textarea and select: .val(). Radio: $("input[name=size]:checked").val(). Checkbox: .prop("checked"), or collect all checked values with .map().

.serialize() turns a form into a URL-encoded string (name=Asha&size=M), ready for $.post. .serializeArray() gives [{ name, value }, ...] which you can turn into an object.

Only fields with a name attribute are serialised, and disabled fields are skipped.

Disable the submit button while sending to prevent double submissions; this.reset() clears the form (it is a DOM method, so call it on the element).

Syntax#

JavaScript Illustrative
$('#form').on('submit', function (e) {
  e.preventDefault();
  const data = $(this).serialize();   // "name=Asha&size=M"
});

Code example: A T-shirt order form#

HTMLA T-shirt order form Runnable
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<form id="order" style="font-family:sans-serif">
  <input name="name" placeholder="Name" value="Asha">
  <select name="colour"><option>White</option><option selected>Black</option></select>
  <label><input type="radio" name="size" value="S"> S</label>
  <label><input type="radio" name="size" value="M" checked> M</label>
  <label><input type="checkbox" name="extras" value="gift" checked> Gift wrap</label>
  <label><input type="checkbox" name="extras" value="express"> Express</label>
  <button type="submit">Order</button>
</form>
<script>
  $(function () {
    $('#order').on('submit', function (e) {
      e.preventDefault();
      const $f = $(this);
      console.log('Name:', $f.find('[name=name]').val());
      console.log('Colour:', $f.find('[name=colour]').val());
      console.log('Size:', $f.find('[name=size]:checked').val());
      const extras = $f.find('[name=extras]:checked').map(function () { return this.value; }).get();
      console.log('Extras:', extras.join(', '));
      console.log('Serialized:', $f.serialize());
    });
  });
</script>
Expected output
Name: Asha
Colour: Black
Size: M
Extras: gift
Serialized: name=Asha&colour=Black&size=M&extras=gift
Opens this example in the full playground

Step-by-step explanation#

  1. The submit handler runs for both the button click and pressing Enter.
  2. preventDefault stops the page from reloading.
  3. [name=size]:checked finds the selected radio.
  4. .map(...).get() turns checked checkboxes into a plain array of values.
  5. serialize() produces a query string with every named, enabled field.

Real-world use case#

A newsletter signup in an ASP.NET MVC site intercepts submit, posts the serialised form with AJAX, and shows a thank-you message without reloading the page.

Common mistakes#

Handling the button click instead of submit

Pressing Enter in a field submits the form without clicking. Handle the form’s submit event.

Fields without name

serialize() ignores inputs without a name attribute.

Trusting client-side values

Anything in the form can be changed in DevTools. Validate again on the server.

Best practices#

  • Handle submit, not click
  • Name every field
  • Disable the button while sending
  • Validate on both client and server

Remember this#

submit + preventDefault = JS controls the form.

:checked for radios and checkboxes.

serialize() = whole form as name=value&….

Practice exercise#

Your task: On submit, convert the form into a plain object { name: "...", email: "..." } using serializeArray() and log it.

Need a hint?
reduce over serializeArray(): (obj, f) => { obj[f.name] = f.value; return obj; }.
Show solution
HTML Runnable
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<form id="f"><input name="name" value="Ravi"><input name="email" value="ravi@example.com"><button>Send</button></form>
<script>
  $(function () {
    $('#f').on('submit', function (e) {
      e.preventDefault();
      const obj = $(this).serializeArray().reduce((o, f) => { o[f.name] = f.value; return o; }, {});
      console.log(obj);   // { name: 'Ravi', email: 'ravi@example.com' }
    });
  });
</script>
Opens this example in the full playground

Mini quiz#

Form Handling quizMultiple choice Question 1 of 3

How do you read the selected radio button value for name="size"?

Score so far: 0/0

Want more? Practise all jQuery MCQs · jQuery interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.