Toggling an Attribute - J Query

Problem
You need a way to toggle all of the checkmarks in a group of checkboxes. Each checkbox should be toggled independently of the others.

Solution

Write a .toggleCheck() plugin that works like the .toggle() and .toggleClass() methods in the jQuery core to allow you to set, clear, or toggle a checkbox or group of checkboxes:

This .toggleCheck() method is built on top of a more general-purpose .toggleAttr()
method that works for any attribute:

Why go to the trouble of building something so general-purpose? Now we can write similartogglers for other attributes with almost no effort. Suppose you need to do the same thing as .toggleCheck(), but now you’re enabling and disabling input controls.You can write a .toggleEnable() in one line of code:

Note how the onValueand offValueparameters let us swap the true and false attribute values, making it easy to talk about “enabling” the element instead of the less intuitive “disabling” that the disabled attribute provides normally.

As another example, suppose we need to toggle a foo attribute where its “on” state is the string value bar, and its “off” state is to remove the attribute. That’s another one-liner:

Discussion

It’s always good to beware of feepingcreaturism (aka creeping featurism). If all we really needed were to toggle checkboxes, we could code the whole thing like this:

That is a bit simpler than our .toggleAttr() method, but it’s only useful for the checked attribute and nothing else. What would we do if we later needed that.toggleEnable() method? Duplicate the whole thing and change a few names?

The extra work in .toggleAttr() buys us a lot of flexibility: we now can write a whole family of attribute togglers as straight forward one-liners.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics