Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

536 LESSON 19: Using JavaScript in Your Pages


The conditional code in the validation JavaScript is the same. The first change I’m mak-
ing is to get rid of the lines that display the alert box and replace them with the lines that
add the appropriate class to the document. The updated JavaScript looks like this:
$(function() {
$("#registrationForm").submit(function (event) {
if (!$(this.name).val()) {
$(this.name).parents("div.required").addClass("error");
event.preventDefault();
}

if (!$("input[name='gender']:checked", this).length) {
$("input[name='gender']", this).parents("div.required").addClass("error");
event.preventDefault();
}
});
});

The trick here is to write the proper selectors to add the error class to the appropriate
element. First, here’s the line that adds the error class to the enclosing div for the Name
field:
$(this.name).parents("div.required").addClass("error");
I start by selecting the Name field. Then I use jQuery’s parents() method to apply the
div.required selector to all the ancestors of the form field. It matches the appropriate
element, and then I use the addClass() method to apply the error class to the div. If
you try this out, you’ll see that when you submit invalid data the labels for the invalid
fields suddenly turn red.
Now let’s look at printing a proper error message on the page. First, I declare a variable
in which to collect the error messages for each field. If a field is invalid, the error mes-
sage is appended to the list. Once all the fields have been validated, if there are any error
messages in the list, the div containing the error messages is formatted and printed at the
top of the form. Here’s the script:
$(function() {
$("#registrationForm").submit(function (event) {
var errors = [];

if (!$(this.name).val()) {
errors.push("<li>You must enter a name.</li>");
$(this.name).parents("div.required").addClass("error");
event.preventDefault();
}

if (!$("input[name='gender']:checked", this).length) {
errors.push("<li>You must select a gender.</li>");
$("input[name='gender']", this).parents("div.required").addClass("error");
event.preventDefault();


Free download pdf