jQuery in Action
Summary
81
Another way that the
val()
method can be used is to cause check box or radio
elements to become checked, or to select options within a
<select>
element. The
syntax of this variant of
val()
is as follows:
Consider the following statement:
$('input,select').val(['one','two','three']);
This statement will search all the
<input>
and
<select>
elements on the page for
values that match any of the input strings: one, two or three. Any check boxes or
radio buttons that are found to match will become checked, and any options that
match will become selected.
radio buttons that are found to match will become checked, and any options that
match will become selected.
This makes
val()
useful for much more than just text elements.
3.5 Summary
In this chapter, we've gone beyond the art of selecting elements and started manip-
ulating them. With the techniques we've learned so far, we can select elements
using powerful criteria, and then move them surgically to any part of the page.
ulating them. With the techniques we've learned so far, we can select elements
using powerful criteria, and then move them surgically to any part of the page.
We can choose to copy elements, or to move them, or even create brand
new elements from scratch. We can append, prepend, or wrap any element or set
of elements on the page. And we've learned how we can treat a single element or
a set of elements the same, leading to powerful yet succinct logic.
of elements on the page. And we've learned how we can treat a single element or
a set of elements the same, leading to powerful yet succinct logic.
With that behind us, we're ready to start looking into more advanced concepts,
starting with the typically messy job of handling events in our pages.
Command syntax: val
val(values)
Causes any check boxes, radio buttons, or options of <select> elements in the wrapped set
to become checked or selected if their values match any of the values passed in the values
array.
to become checked or selected if their values match any of the values passed in the values
array.
Parameters
values
(Array) An array of values that will be used to determine which elements are to
be checked or selected.
be checked or selected.
Returns
The wrapped set.
The wrapped set.