TExcelTAD
Home › jQuery › jQuery Forms

jQuery Forms

Forms are where users give you data, and jQuery has a compact toolkit for them: reading and setting values, reacting to changes, validating, and turning a whole form into a string or array ready to send to a server.

Reading and setting values with val()

.val() works on every kind of form control, but what it returns depends on the control:

Control .val() returns Set with
<input type="text">, <textarea> The text .val("text")
<select> The selected option's value .val("v2")
<select multiple> An array of values (empty array if none) .val(["a", "c"])
Checkbox / radio Its value attribute (not whether it is checked) .prop("checked", true)

For checkboxes and radios, ask about state instead:

js
$("#agree").is(":checked");                 // true / false
$("input[name=size]:checked").val();        // value of the selected radio
html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 14px; }
    label { display: block; margin: 4px 0; }
  </style>
</head>
<body>
  <label>Name <input id="name" value="Ana"></label>
  <label>Size
    <select id="size"><option value="s">Small</option><option value="m" selected>Medium</option><option value="l">Large</option></select>
  </label>
  <label>Toppings
    <select id="tops" multiple size="3"><option>cheese</option><option>olives</option><option>basil</option></select>
  </label>
  <label><input type="radio" name="crust" value="thin" checked> thin</label>
  <label><input type="radio" name="crust" value="thick"> thick</label>
  <label><input type="checkbox" id="extra"> Extra hot</label>
  <button id="read">Read</button> <button id="fill">Fill</button>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#read").on("click", function () {
      console.log({
        name: $("#name").val(),
        size: $("#size").val(),
        tops: $("#tops").val(),
        crust: $("input[name=crust]:checked").val(),
        extra: $("#extra").is(":checked")
      });
    });
    $("#fill").on("click", function () {
      $("#name").val("Ben");
      $("#size").val("l");
      $("#tops").val(["cheese", "basil"]);
      $("input[name=crust]").val(["thick"]);   // array on radios/checkboxes checks matching values
      $("#extra").prop("checked", true);
    });
  </script>
</body>
</html>

Tip: Passing an array to .val() on a group of checkboxes or radios checks the ones whose value is in the array.

Form events

Event Fires when
input The value changes on every keystroke / edit
change A text field loses focus after changing, or a select/checkbox/radio changes
focus / blur The field gains / loses focus (focusin/focusout also bubble)
submit The form is submitted (Enter key or submit button) — attach to the <form>

Validating on submit

Always listen to submit on the form, not click on the button — that also catches the Enter key. Call e.preventDefault() to stop the page from reloading.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 14px; }
    .field { margin-bottom: 8px; }
    .field input { padding: 5px; border: 1px solid #aaa; border-radius: 4px; }
    .field.error input { border-color: #c62828; background: #fdecea; }
    .msg { color: #c62828; font-size: 12px; margin-left: 6px; }
    #ok { color: #2e7d32; }
  </style>
</head>
<body>
  <form id="signup" novalidate>
    <div class="field"><input name="email" placeholder="Email"></div>
    <div class="field"><input name="password" type="password" placeholder="Password (8+ chars)"></div>
    <div class="field"><label><input type="checkbox" name="terms"> I accept the terms</label></div>
    <button type="submit">Sign up</button>
    <span id="ok"></span>
  </form>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    function setError($input, message) {
      const $field = $input.closest(".field");
      $field.toggleClass("error", !!message).find(".msg").remove();
      if (message) $field.append($("<span class='msg'>").text(message));
      return !message;
    }

    $("#signup").on("submit", function (e) {
      e.preventDefault();
      const $f = $(this);
      const $email = $f.find("[name=email]");
      const $pw = $f.find("[name=password]");
      const $terms = $f.find("[name=terms]");

      const ok = [
        setError($email, /^\S+@\S+\.\S+$/.test($email.val()) ? "" : "Enter a valid email"),
        setError($pw, $pw.val().length >= 8 ? "" : "At least 8 characters"),
        setError($terms, $terms.is(":checked") ? "" : "Required")
      ].every(Boolean);

      $("#ok").text(ok ? "Welcome aboard! ✔" : "");
      console.log("valid:", ok);
    });

    // clear an error as soon as the user edits the field
    $("#signup").on("input change", "input", function () {
      setError($(this), "");
    });
  </script>
</body>
</html>

Serializing a form

To send a form with AJAX you need its data in a transport format. jQuery has two helpers; both include only successful controls — fields with a name, not disabled, and (for checkboxes/radios) checked.

Method Returns
.serialize() A URL-encoded string: "name=Ana&size=m"
.serializeArray() An array of { name, value } objects
$.param(obj) Encodes a plain object the same way as serialize()
html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
  <form id="order">
    <input name="customer" value="Ana Lima">
    <select name="drink"><option>tea</option><option selected>coffee</option></select>
    <label><input type="checkbox" name="extras" value="milk" checked> milk</label>
    <label><input type="checkbox" name="extras" value="sugar"> sugar</label>
    <input name="note" value="ignored" disabled>
    <button>Show data</button>
  </form>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#order").on("submit", function (e) {
      e.preventDefault();
      console.log("serialize():", $(this).serialize());
      console.log("serializeArray():", $(this).serializeArray());

      // turn the array into an object (repeated names become arrays)
      const data = {};
      $.each($(this).serializeArray(), function (_, field) {
        if (field.name in data) data[field.name] = [].concat(data[field.name], field.value);
        else data[field.name] = field.value;
      });
      console.log("object:", data);
      console.log("$.param:", $.param({ q: "jquery forms", page: 2 }));
    });
  </script>
</body>
</html>

Notice that the disabled note field and the unchecked sugar box are missing, and the space in "Ana Lima" is encoded as %20. (When $.ajax later sends such a string as a form body, it converts %20 to +, the traditional form encoding.)

Note: File inputs are not included by .serialize(). To upload files with AJAX, use a FormData object (new FormData(formElement)) with $.ajax({ data: fd, processData: false, contentType: false }).

Test yourself

What does .val() return for a <select multiple>?

  1. The first selected value
  2. A comma-separated string
  3. An array of selected values
  4. The number of selected options

Why listen to submit on the form instead of click on the submit button?

  1. click does not exist on buttons
  2. submit also fires when the user presses Enter in a field
  3. submit is faster
  4. click cannot call preventDefault()

Which field is included by $("form").serialize()?

  1. <input value="x"> without a name
  2. A disabled named input
  3. An unchecked named checkbox
  4. A named text input that is enabled