Created
February 8, 2010 21:20
-
-
Save mathiasbynens/298591 to your computer and use it in GitHub Desktop.
toggleAttr() jQuery plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* toggleAttr() jQuery plugin | |
* @link http://github.com/mathiasbynens/toggleAttr-jQuery-Plugin | |
* @description Used to toggle selected="selected", disabled="disabled", checked="checked" etc… | |
* @author Mathias Bynens <http://mathiasbynens.be/> | |
*/ | |
jQuery.fn.toggleAttr = function(attr) { | |
return this.each(function() { | |
var $this = $(this); | |
$this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr); | |
}); | |
}; |
I just wrote a similar plugin which acts more like .toggle() and .toggleClass(), which can take a boolean as a further argument. https://gist.github.com/tremby/6804168
You could also allow an option to explicitly specify if the attribute is on or off like this:
$.fn.extend({
toggleAttr: function (attr, turnOn) {
var justToggle = (turnOn === undefined);
return this.each(function () {
if ((justToggle && !$(this).is("[" + attr + "]")) ||
(!justToggle && turnOn)) {
$(this).attr(attr, attr);
} else {
$(this).removeAttr(attr);
}
});
}
});
Then use like this:
$(selector).toggleAttr("required");
$(selector).toggleAttr("required", true);
$(selector).toggleAttr("required", false);
That way the API is similar to the way .toggleClass()
is implemented.
$(selector).attr('disabled', function (_, attr) { return !attr });
This works (at least to enable or disable fields) as well!
@viicviicviic
jQuery(selector).attr('required', function (_, attr) { return !attr });
This working for required too
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for this. i modified this a little for my needs
Usage: