Here are 3 helper jQuery functions from my ever-mutating util.js file.
jQuery.check( – Checks or unchecks a checkbox input field based on the boolean you pass it. Very simple, but a handy shortcut. Does not trigger any events like click or change by design.
jQuery.enable()/jQuery.disable() – Does 3 things:
- Adds or removes the “disabled” class on all matched elements.
- Sets the disabled HTML DOM property on elements which support it (input and select).
- Adds or removes the “disabled” class for any labels whose
forattribute matches the ID of an affectedinput.
That last little side effect is what makes these 2 helper functions so handy. I like to subtly theme label.disabled to indicate when a field is disabled.
(function(){ jQuery.fn.extend({ check: function(on) { return this.each(function() { this.checked = true ? on !== false : false; });}, enable: function() { this.removeClass('disabled'); return this.each(function() { if (this.disabled !== undefined) { // Only disable elements that support it this.disabled = false; // Affect labels as well $("label[for="+this.id+"]").removeClass("disabled"); } }); }, disable: function() { this.addClass('disabled'); return this.each(function() { if (this.disabled !== undefined) { // Only disable elements that support it this.disabled = true; // Affect labels as well $("label[for="+this.id+"]").addClass("disabled"); } }); } }); })();
Would love to hear feedback.