Web Development with jQuery®

(Elliott) #1

Filtering a Selection (^) ❘ 41
Next, you disable the submit button so that the user cannot become impatient and click it
repeatedly, sending multiple requests to join your newsletter to your server.
input.attr('disabled', true);
Another way of setting the disabled attribute is to call the attr() method like this:
input.attr('disabled', 'disabled');
And you might prefer this method because it is also technically the way that XHTML says that
boolean HTML attributes should be done. But jQuery supports doing this either way, by passing a
boolean true or false or by passing the value disabled. Likewise, to disable the disabled attribute,
you can either pass false in a call, such as attr('disabled', false), or you can remove the attribute
all together by calling removeAttr('disabled').
In the next line you make a call to contactNewsletterForm.validate() to see if the form validates.
This method returns a boolean value that indicates either yes, all the required fi elds have been
provided, or no, there is missing data.
if (!contactNewsletterForm.validate())
{
If all the required data has not been provided, then users sees an alert() message, asking them to
provide both their fi rst and last names.
alert("Please provide both your first and last name");
Then the submit button is re-enabled so that users can attempt to submit the form again.
input.removeAttr('disabled');
I do this by removing the disabled attribute, but as mentioned before you can also call
attr('disabled', false) and this provides the same functionality. Finally, the preventDefault()
method is called on the event object to prevent the default action of the submit button, which is to
submit the form.
event.preventDefault();
If, however, all the data has been provided, then the form is submitted by calling submit() on the


element. You might wonder why this is necessary. Because event.preventDefault() is supposed
to prevent the default action, wouldn’t not calling it allow the default action? In this case, it would not
because the default action is also prevented by disabling the submit button by enabling the disabled
attribute, and because the button has been disabled, you now have to explicitly submit the form.
}
else
{
$('form#contactNewsletterForm').submit();
}
Next, you examine what happens inside the validate() method. First, you set up a variable that
keeps track of whether the required fi elds have been provided. You start off by assuming that the
[http://www.it-ebooks.info](http://www.it-ebooks.info)
Free download pdf