jQuery in Action
272
CHAPTER 9
Prominent, powerful, and practical plugins
Bring up this page, and leaving the controls in their initial state, click the Get
Successful Values button. This causes the following command to be executed:
Successful Values button. This causes the following command to be executed:
$('#testForm *').fieldValue()
This creates a wrapped set of all children of the test form, including all the labels
and
and
<div>
elements, and executes the
fieldValue()
command on it. Because this
command ignores all but form controls and, without a parameter, only includes
successful controls, the results displayed on the page are
successful controls, the results displayed on the page are
['some text','Three','cb.2','radio.2','Lorem ipsum dolor sit amet,
consectetuer adipiscing elit.']
As expected, the values for the text field, the dropdown, the checked check box,
the checked radio button, and the text area are collected into an array.
the checked radio button, and the text area are collected into an array.
Now go ahead and click the Get All Values button, which executes the command
$('#testForm *').fieldValue(false)
The
false
parameter to this command instructs it not to exclude unsuccessful
controls, and we can see the more inclusive results as follow:
['some text','Three','One','Two','Three','Four','Five','cb.1',
'cb.2','cb.3','radio.1','radio.2','radio.3','Lorem ipsum dolor
sit amet, consectetuer adipiscing elit.','','','','']
Note that not only have the values for the unchecked check boxes and radio but-
tons been included but also empty strings for the values for the four buttons.
tons been included but also empty strings for the values for the four buttons.
Now, have some fun playing around with the values of the controls and observ-
ing the behavior of the two forms of the
fieldValue()
command until you feel
you've got it down.
Getting the values of the controls in an array can be useful when we want to
process the data in some way; if we want to create a query string from the data, the
serialize commands will do that for us. Let's see how.
serialize commands will do that for us. Let's see how.
Serializing control values
When we want to construct properly formatted and encoded query strings from
the values of form controls, we turn to the
the values of form controls, we turn to the
formSerialize()
and
fieldSerialize()
commands. Both of these wrapper methods collect values from the wrapped set
and return a formatted query string with the names and values properly
and return a formatted query string with the names and values properly
URL
-
encoded. The
formSerialize()
method accepts a form in the wrapped set and
serializes all of the successful child controls. The
fieldSerialize()
command seri-
alizes all of the controls in the wrapped set and is useful for serializing only a por-
tion of a form.
tion of a form.
The syntaxes of these commands are as follow: