Web Development with jQuery®

(Elliott) #1

(^40) ❘ CHAPTER 2 SELECTING AND FILTERING
In Example 2-2, you see one way you might use the find() method, to validate input for a simple
newsletter sign-up form. The text inputs in the HTML form use the HTML5 required attribute to
indicate that they are required fi elds; some browsers with support for HTML5 fi elds and attributes
will already prevent the user from submitting the form without required input. The JavaScript that
you implement with this example provides a little more functionality; however, it also prevents the
form from being submitted multiple times. In Example 2-2.js, you create a simple JavaScript object
literal; this is one way of creating a simple JavaScript custom object. An object called contactNews-
letterForm is created, which contains the logic necessary for your newsletter sign-up form. It con-
tains two methods, one called ready() and one called validate(). The ready() method is executed
when the document’s DOMContentLoaded event has fi red, which as you already know is mapped to the
jQuery event with the much simpler name of ready. So, as soon as the DOM has loaded, this event
will be called, and you can do things with the DOM. contactNewsletterForm.ready() attaches a
single event to the submit button. It does this by fi rst selecting the with an id selector,
input#contactNewsletterFormSubmit, and then it calls the method click() to attach an onclick
event to that element. This allows you to intercept and control what happens when the user
clicks the submit button.
ready : function()
{
$('input#contactNewsletterFormSubmit').click(
function(event)
{
var input = $(this);
input.attr('disabled', true);
if (!contactNewsletterForm.validate())
{
alert("Please provide both your first and last name");
input.removeAttr('disabled');
event.preventDefault();
}
else
{
$('form#contactNewsletterForm').submit();
}
}
);
},
Within the function that is attached to the click event of the submit button, the fi rst thing you
do is create a variable called input with a call to jQuery with the special this keyword as its fi rst
and only argument. As mentioned earlier in this chapter, when an event is called, this refers to
the element the event occurred on, but this is not jQuery-enabled. To make it jQuery-capable,
all you have to do is to call jQuery with this as the argument. This is how you enable any ele-
ment in the JavaScript DOM to be jQuery-enabled, not just the special this keyword in the con-
text of events.
var input = $(this);
http://www.it-ebooks.info

Free download pdf