Setting, Retrieving, and Removing Attributes (^) ❘ 93
FIGURE 4-1
In the JavaScript source code, the fi rst thing you do is set up a reusable method to retrieve the cor-
rect check box element. This method is aptly named getCheckbox().
var getCheckbox = function()
{
var input = $('input[name="documentAttributeMarx"]:checked');
if (input && input.length)
{
return input;
}
return $('input[name="documentAttributeMarx"]:first')
.attr('checked', true);
};
First, you use a selector to fi nd the right set of check boxes, which is done with an attribute selector,
input[name="documentAttributeMarx"], and then is further narrowed down using jQuery’s :checked
pseudo-class. The attribute selector selects all four radio elements, and then the selection is
immediately narrowed to include only those with the checked="checked" attribute, indicating a user
selection. The function makes sure that an element was found with the line input && input.length;
if there is an element, it is returned. If there is no element, the check box collection
is selected again and this time is narrowed to the fi rst item present in the selection using jQuery’s
:first pseudo-class. The fi rst item is explicitly checked with attr('checked', true). You can also
use attr('checked', 'checked'), if you like; both methods result in the check box being checked.
The method then returns the fi rst element, ensuring that the method works whether an
element is checked.
The next block of code handles what happens when you click the button labeled Set Attribute: