ptg16476052
532 LESSON 19: Using JavaScript in Your Pages
I’m still preventing the form’s submission, and now I’m using the console.log()
method to log the value of $(this.name).val(). The console.log() method is pro-
vided as a convenience so that you can print out your own messages to the Console tab
in the Development Tools window. In this case, I want to print out the value of the form
field. Remember that this is an object representing the form. The form object has prop-
erties representing each of its fields, so I can access a field with the name “name” using
this.name. jQuery provides the val() method to normalize accessing the values of form
fields. So, $(this.name).val() returns the current value of the field named “name” in
the form. That line prints it on the console.
Using this information and an if statement, you can test the contents of name to see
whether a na me has been entered:
if (!$(this.name).val()) {
event.preventDefault();
alert("You must enter a name.");
}
The expression in the if statement evaluates the value of the form field in a Boolean con-
text. So if the field’s value is null or an empty string, the expression will be false. In that
case, the function displays an error message and prevents the form from being submitted.
If the name is valid, the next step is to validate the gender radio button group. Validation
of these fields differs slightly because radio button groups consist of multiple fields with
the same name. So in this case, I need to alter my selector to access the value of the radio
button field. Remember that only one element in a set of radio buttons can be selected. I
can use the CSS selector for attribute values to locate the selected radio button. The code
to validate the radio button looks like this:
if (!$(this).find("input[name='gender']:checked").length) {
event.preventDefault();
alert("You must select your gender.");
}
I access the Gender field on the form the same way I accessed the Name field. Then I
used the jQuery find method to search for elements with the “checked” attribute checked
using the :checked selector. I could also pass the context for a jQuery query as a second
argument to the jQuery method, like this:
$("input[name='gender']:checked", this)
If neither radio button is selected, the length of the matched set will be zero and therefore
be false in the context of the if statement, and the error message will be displayed.
▼
▼