jQuery in Action
Putting events (and more) to work
119
After locating the text boxes (with a selector that reads "find all
<input>
elements
of type
text
that are within
<span>
elements possessing a
price
attribute"), we
assign a change handler that finds the
<span>
to be updated and sets its text con-
tent to the computed value; the expression
$('~
span:first',this)
locates the
first sibling of
this
that's a
<span>
element. The computation is made by obtain-
ing the value of the text box and multiplying it by the value of the
price
attribute
on the parent
<span>
.
If any of these rather advanced selector expressions has you scratching your
head, it might be a good time to review the selector syntax presented in chapter 2.
Before we let the user interact with our page, we have one more thing that we
need to do. Remember how we left the
<span>
elements that are to contain the
computed values blank? Now it's time to fill those in.
The values of the quantity text boxes were preset to 1, so all we need to do is to
perform the same computation that occurs when the values are changed. But we
don't want to repeat any code so we trigger the change handler on the text boxes
and let that change handler do its thing.
don't want to repeat any code so we trigger the change handler on the text boxes
and let that change handler do its thing.
$('span[price] input[type=text]').change();
With that, we've completed whipping up the appetizer order form--at least to the
point where we've met our stated goals. This example exposed us to some very
important lessons:
point where we've met our stated goals. This example exposed us to some very
important lessons:
It showed us how to establish click and change handlers on elements that can
be used to effect whatever user interface changes we want when triggered.
be used to effect whatever user interface changes we want when triggered.
We saw how to trigger handlers under script control to avoid both repeated
code and the need to factor common code out into global named functions.
code and the need to factor common code out into global named functions.
We were exposed to some mighty fancy selectors used to pick and choose
which elements we wanted to perform operations on.
which elements we wanted to perform operations on.
The complete code for the page is shown in listing 4.8.
<html>
<head>
<title>Bamboo Asian Grille - Online Order Form</title>
<link rel="stylesheet" type="text/css" href="bamboo.css">
<script type="text/javascript"
src="../../scripts/jquery-1.2.1.js"></script>
<script type="text/javascript">
$(function(){
Listing 4.8 Complete code for the appetizer order form