jQuery in Action
240
CHAPTER 8
Talk to the server with Ajax
We've changed the
id
of the
<body>
tag (primarily so that we can use it as a switch
within the
CSS
stylesheet used by multiple versions of the page) and added the
two empty and disabled dropdowns.
To add the new behaviors associated with these controls to the page, we also
need to enhance our ready handler. The new ready handler, once again with
changes highlighted in bold, is as follows:
changes highlighted in bold, is as follows:
$(function(){
$('#styleDropdown')
.change(function(){
var styleValue = $(this).val();
$('#detailsDisplay').load(
'getDetails.jsp',
{ style: styleValue }
);
adjustColorDropdown();
})
.change();
$('#colorDropdown')
.change(adjustSizeDropdown);
});
These changes are minor but significant. First, we make a call to a function
named
named
adjustColorDropdown()
within the change listener for the styles dropdown
b
. This will trigger any change required for the state and content based upon the
value of the style selected.
We then add a listener to the new colors dropdown
c
to adjust the state and
content of the size dropdown when the color dropdown changes value. This lis-
tener is set to be a function named
tener is set to be a function named
adjustSizeDropdown()
.
That's all simple enough, but we still haven't written the functions that effect
the changes to the state and content of the dependent dropdowns. Let's tackle the
color dropdown first with the definition of the
color dropdown first with the definition of the
adjustColorDropdown()
function.
function adjustColorDropdown() {
var styleValue = $('#styleDropdown').val();
var dropdownSet = $('#colorDropdown');
if (styleValue.length == 0) {
dropdownSet.attr("disabled",true);
$(dropdownSet).emptySelect();
adjustSizeDropdown();
}
else {
dropdownSet.attr("disabled",false);
$.getJSON(
'getColors.jsp',
{style:styleValue},
Triggers state adjustment
of color dropdown
of color dropdown
b
Binds change listener
to color dropdown
to color dropdown
c
Enables or disables
the color dropdown
the color dropdown
b
Empties disabled dropdown and
clears dependent dropdown
clears dependent dropdown
c
Gets color values
based on style
based on style
d