Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 56 ยท Forms

Working with Form Controls

Read and set form values with jQuery: .val() for inputs, selects, checkboxes and radios, :checked and :selected, disabling, focus, .serialize() and .serializeArray().

Forms are where most web applications meet their users, and jQuery has a compact set of tools for them. A single method, .val(), reads and writes the value of text boxes, drop-downs and multi-selects alike. Selectors such as :checked find the options a user picked. And two methods, .serialize() and .serializeArray(), turn a whole form into data you can send to a server or inspect in code.

This lesson covers all of them, plus the practical details that cause bugs: how checkboxes and radios differ from text fields, how to disable and focus controls properly, and which fields serialization leaves out. You should know how to select elements and how attributes differ from properties.

One method, many controls

Text inputs .val() returns a string.
Select Returns the chosen option's value.
Multi-select Returns an array of values.
Radio, checkbox Use :checked, not .val().
1 / 2

Reading and setting values with .val()

Called with no argument, .val() returns the value of the first element in the collection. Called with an argument, it sets the value on every element.

JavaScript
var name = $("#name").val();       // read
$("#name").val("Ada");             // write
$("#name").val("");                // clear

The result is always a string for text-like controls, even for <input type="number">. Convert it yourself with Number() or parseFloat() before doing arithmetic, otherwise "2" + "3" gives "23".

Like other setters, .val() accepts a function. It receives the index and the current value, which is handy for transforming a whole set of fields:

JavaScript
$("input.trim").val(function (index, current) {
  return current.trim();
});
Reading and writing text values

Select boxes and multi-selects

For a single <select>, .val() returns the value of the chosen option (or its text if the option has no value attribute). To select an option, pass the value you want.

For <select multiple>, .val() returns an array of the chosen values, or an empty array when nothing is selected. Setting it takes an array too, which selects exactly those options and clears the rest.

JavaScript
$("#country").val("de");
$("#tags").val(["css", "html"]);     // multi-select: choose two
var picked = $("#tags").val();       // ["css", "html"]

To get the visible text of the selected option rather than its value, select the option itself: $("#country option:selected").text(). The :selected selector is a jQuery extension; the CSS-friendly equivalent is $("#country option").filter(":checked"), and in plain JavaScript you would read select.selectedOptions.

Checkboxes and radio buttons

A checkbox's .val() is the string in its value attribute (which is "on" when the attribute is missing). That string does not tell you whether the box is ticked. The state lives in the checked property, so use .prop("checked") to read or set it, and :checked to find ticked controls.

JavaScript
var isSubscribed = $("#news").prop("checked");   // true or false
$("#news").prop("checked", true);                // tick it

var colors = $("input[name='color']:checked");   // ticked checkboxes
var size = $("input[name='size']:checked").val(); // value of the chosen radio

Do not use .attr("checked") for the live state. The attribute only describes the initial state from the HTML, while the property follows what the user does.

To collect the values of every ticked checkbox in a group, combine :checked with .map():

JavaScript
var values = $("input[name='toppings']:checked").map(function () {
  return this.value;
}).get();

.get() at the end converts the jQuery object into a normal array.

Checkboxes, radios and selects

The summary template uses .html() only for a fixed string with empty <b> tags; the actual values are inserted with .text(), a habit worth keeping (see getting and setting content).

Disabling, enabling and focus

Disabled is a property, so use .prop("disabled", true) and .prop("disabled", false). A disabled control cannot be focused or clicked, and it is not submitted with the form. If you only want to prevent editing but still send the value, use readonly instead: .prop("readonly", true).

Focus is a part of usability. After showing an error, move the cursor to the field that needs attention; after opening a dialog, focus its first control. Call .trigger("focus") on the target, or use the DOM method directly with $("#email")[0].focus(). The event shorthand .focus() with no arguments still works but has been deprecated since jQuery 3.3, so .trigger("focus") is the preferred spelling. To highlight the existing text as well, call the DOM method $("#email")[0].select().

JavaScript
$("#submit").prop("disabled", true);
$("#email").trigger("focus");
$("#email").prop("readonly", true);

Serializing a form

.serialize() builds a URL-encoded query string from the successful controls of a form, ready to be sent as the body of a request:

JavaScript
$("#signup").serialize();
// "name=Ada%20Lovelace&plan=pro&tags=css&tags=html"

.serializeArray() returns the same information as an array of { name, value } objects, which is easier to process in code:

JavaScript
$("#signup").serializeArray();
// [ { name: "name", value: "Ada Lovelace" }, { name: "plan", value: "pro" }, ... ]

Both follow the browser's rules for what is "successful":

  • A control needs a name attribute; fields without one are skipped.
  • Disabled controls are skipped.
  • Unchecked checkboxes and unselected radios are skipped.
  • Submit buttons and <input type="file"> are skipped.

Because of the last rule, .serialize() is not enough for file uploads; use FormData for those. A common task is turning the array into a plain object. Be aware that repeated names (such as several checked boxes) must be gathered into an array, otherwise the last one wins.

Serialize a form and build an object

Notice that neither the nickname nor the disabled coupon shows up, and the tags key collapses into an array only because we wrote code for it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does $("#tags").val() return for a <select multiple> with two options chosen?

    For a multi-select, .val() returns an array of values (an empty array when nothing is selected).
  2. 2. Which expression correctly tells you whether a checkbox is ticked right now?

    The checked property reflects the live state. The attribute only holds the initial state and val() returns the value string.
  3. 3. Which control is skipped by .serialize()?

    Disabled controls, controls without a name, unchecked boxes and submit buttons are not successful controls, so serialization leaves them out.
  4. 4. You want to stop the user from editing a field but still submit its value. What do you set?

    A readonly field cannot be edited but is still submitted. A disabled field is not submitted at all.
  5. 5. How do you get the chosen radio button's value in the group named size?

    Without :checked you get the value of the first radio in the group, regardless of the selection.

Summary

  • .val() reads the first element's value and writes to all matched elements; text controls always give strings.
  • Single selects return one value, multi-selects return an array; use option:selected to get the visible text.
  • For checkboxes and radios read the live state with .prop("checked") and find choices with :checked.
  • Use .prop("disabled") to block a control (it is not submitted) and readonly to block editing but keep the value.
  • .serialize() returns a query string and .serializeArray() an array of { name, value }; both skip unnamed, disabled and unchecked controls.

Now put these tools to work in Form Validation.