Web Development with jQuery®

(Elliott) #1

(^42) ❘ CHAPTER 2 SELECTING AND FILTERING
user did provide every required fi eld by assigning true to the variable hasRequiredValues. Then you
make a selection, and you select the

element with the id name contactNewsletterForm. As
presented earlier in this section, it’s good to establish a context for your selections, as this can speed
up selections tremendously. In this case, this newsletter sign-up form could be part of a much larger
document. You don’t want to make the mistake of assuming that your code will or will not be part
of a much larger document; it’s better to always plan for the most fl exible approach possible. Your
client or employer might change its mind and decide that it wants to move a form, or include a form,
to or within places that you hadn’t anticipated when you fi rst built your form. In these situations,
it’s best to have fl exible programming that can adapt to changes quickly and seamlessly. Part of
providing the best foundation for fl exible (and reusable) programming like this is to establish good
naming conventions, as discussed back in Chapter 1. Don’t choose names that are too simple and
could easily confl ict with other features. You may be annoyed by the verbosity of the names, but you
will be pleased with the ease with which you can move and integrate features within your website or
web-based application.
validate : function()
{
var hasRequiredValues = true;
$('form#contactNewsletterForm').find('input, select, textarea').each(
function()
{
var node = $(this);
if (node.is('[required]'))
{
var value = node.val();
if (!value)
{
hasRequiredValues = false;
return false;
}
}
}
);
return hasRequiredValues;
}
};
So, begin by selecting the form because it has an established id name; it is a pivot point for quickly
making other selections. You look inside your element for other elements. In this case you
search for ,