jQuery in Action
80
CHAPTER 3
Bringing pages to life with jQuery
checked or unchecked states of check boxes and radio buttons, and will return the
value of check boxes or radio buttons as defined by their
value of check boxes or radio buttons as defined by their
value
attribute, regard-
less of whether they are checked or not.
For radio buttons, the power of jQuery selectors combined with the
val()
method saves the day. Consider a form with a radio group (a set of radio buttons
with the same name) named
with the same name) named
radioGroup
and the following expression:
$('[name=radioGroup]:checked').val()
This expression returns the value of the single checked radio button (or
unde-
fined
if none is checked). That's a lot easier than looping through the buttons
looking for the checked element, isn't it? Since
val()
only considers the first ele-
ment in a wrapped set, it's not as useful for check box groups where more than
one control might be checked.
one control might be checked.
If we want to obtain the values with which the controls would be submitted
through a form submission, we'll be much better off using the
serialize()
com-
mand (which we'll see in chapter 8) or the official Form Plugin.
Another common operation we'll perform is to set the value of a form ele-
ment. The
val()
command is also used for this purpose by supplying a value. Its
syntax is as follows:
Like the
get
variant of this command, this function has its limitations. It can't set
multiple values into a multiselect list, for example. This is the reason that much
more robust functionality is available in the Form Plugin. In addition to lifting
the limitations mentioned so far, it's capable of such operations as retrieving an
array of values for check box groups, serializing the elements in the wrapped set,
clearing fields, and even converting a
more robust functionality is available in the Form Plugin. In addition to lifting
the limitations mentioned so far, it's capable of such operations as retrieving an
array of values for check box groups, serializing the elements in the wrapped set,
clearing fields, and even converting a
DOM
form into a format suitable for use
with Ajax.
Command syntax: val
val(value)
Sets the passed value as the value of all matched form elements
Parameters
value
(String) A string that's set as the value property of each form element in the
wrapped set
wrapped set
Returns
The wrapped set
The wrapped set