Java Reference
In-Depth Information
}
function handleResponse(response) {
if (response.available) {
alert(response.searchTerm + " is available!");
} else {
alert("We're sorry, but " + response.searchTerm +
" is not available.");
}
}
$("#usernameAvailability").on("click", checkUsername);
$("#emailAvailability").on("click", checkEmail);
</script>
</body>
</html>
Save this as
ch16 _ example2.html
in your web server's root directory. Like the examples in Chapter
14, this file must be hosted on a web server in order to work correctly. Open your web browser to
http://yourserver/ch16_example2.html
.
Type
jmcpeak
into the Username field and click the Check
Availability link next to it. You'll see an
alert
box telling you the username is taken.
Now type
someone@xyz.com
in
the Email field and click the Check Availability link next to it. Again,
you'll be greeted with an
alert
box stating that the e‐mail is already in use. Now input your own
username and e‐mail into these fields and click the appropriate links. Chances are an
alert
box will
tell you that your username and/or e‐mail is available (the usernames
jmcpeak
and
pwilton
and the e‐
The HTML and CSS in this example are identical to
ch14 _ example1.html
. So, let's dig into the
JavaScript starting with the final two lines of code that set up the
click
event listeners on the Check
Availability links. You could easily reuse the code from the original, but jQuery makes it a little easier
to set up events:
$("#usernameAvailability").on("click", checkUsername);
$("#emailAvailability").on("click", checkEmail);
You select the elements by their ID and use jQuery's
on()
method to register the
click
event on those
elements. Once again, checking the username value is the job of
checkUsername()
, and
checkEmail()
is responsible for checking the e‐mail value.
The new
checkUsername()
function is somewhat similar to the original. You start by preventing the
default behavior of the event by calling
e.preventDefault()
:
function checkUsername(e) {
e.preventDefault();
Next, you need to get the value of the appropriate
<input/>
element. You haven't learned how to
retrieve the value of a form control with jQuery, but don't worry—it's very simple:
var userValue = $("#username").val();
if (!userValue) {