jQuery in Action

118
CHAPTER 4
Events are where it happens!
To this element, we do the following:
Use the
attr()
command to set its disabled state to correspond to the
inverse of the check box state.
Apply a
CSS
color
value so that the text is invisible when the control is dis-
abled. (Note that this doesn't work on all browsers--some like Opera and
Internet Explorer don't allow us to override the color of disabled fields.)
Set the value to 1. If we're enabling the control, this is the default value we
want to use; when disabling the field, we want to revert to this default.
Call the change handler of the text box (which we haven't defined yet, but
don't worry because that's next). This change handler will compute the
price for the appetizer and display it. Because we changed the value under
the covers (to 1), we need to call this handler to ensure that the price dis-
play is accurate.
Employ the
each()
method to obtain a reference to the element and assign
focus to that element if the check box is in checked state. Don't you just
love closures that give us access to the
checked
local variable?
NOTE
When pondering what type of event to handle for the check boxes, you
may initially have thought of capturing change events as opposed to click
events. For our scheme to work, we need to be immediately notified when
the state of a check
box changes. Immediate notification occurs within
Safari and the Mozilla-based browsers, but Internet Explorer does not
trigger change events until after focus has been blurred from the control,
making the change event unsuitable for this use; instead, we rely on the
click event.
Now let's turn our attention to the change handler for the text box. When the
value in the text box changes, we want to recompute and display the cost of the
appetizer--a simple calculation made by multiplying the price of one appetizer
by the quantity.
The statement to add the change handler is as follows:
$('span[price] input[type=text]').change(function(){
$('~ span:first',this).text(
$(this).val() *
$(this).parents("span[price]:first").attr('price')
);
});


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.