jQuery in Action
Adding new wrapper methods
201
That's all there is to it, but (isn't there always a but?) there are some techniques
we should be aware of when creating more involved jQuery wrapper methods.
Let's define a couple more plugin methods of greater complexity to examine
those techniques.
Let's define a couple more plugin methods of greater complexity to examine
those techniques.
7.4.1 Applying multiple operations in a wrapper method
Let's develop another new plugin method that performs more than a single oper-
ation on the wrapped set. Imagine that we need to be able to flip the read-only
status of text fields within a form and to simultaneously and consistently affect the
appearance of the field. We could easily chain a couple of existing jQuery com-
mands together to do this, but we want to be neat and tidy about it and bundle
these operations together into a single method.
ation on the wrapped set. Imagine that we need to be able to flip the read-only
status of text fields within a form and to simultaneously and consistently affect the
appearance of the field. We could easily chain a couple of existing jQuery com-
mands together to do this, but we want to be neat and tidy about it and bundle
these operations together into a single method.
We'll name our new command
setReadOnly()
, and its syntax is as follows:
The implementation of this plugin is shown in listing 7.3 and can be found in the
file chapter7/jquery.jqia.setreadonly.js.
file chapter7/jquery.jqia.setreadonly.js.
(function($){
$.fn.setReadOnly = function(readonly) {
return this.filter('input:text')
.attr('readonly',readonly)
.css('opacity', readonly ? 0.5 : 1.0);
}
})(jQuery);
Command syntax: setReadOnly
setReadOnly(state)
Sets the read-only status of wrapped text fields to the state specified by state. The opacity
of the fields will be adjusted: 100% if not read-only or 50% if read-only. Any elements in the
wrapped set other than text fields are ignored.
of the fields will be adjusted: 100% if not read-only or 50% if read-only. Any elements in the
wrapped set other than text fields are ignored.
Parameters
state
(Boolean) The read-only state to set. If true, the text fields are made read-only;
otherwise, the read-only status is cleared.
otherwise, the read-only status is cleared.
Returns
The wrapped set.
The wrapped set.
Listing 7.3
Implementation of the setReadOnly() plugin method