Skip to content

Instantly share code, notes, and snippets.

@mathiasbynens
Created February 8, 2010 21:20
Show Gist options
  • Save mathiasbynens/298591 to your computer and use it in GitHub Desktop.
Save mathiasbynens/298591 to your computer and use it in GitHub Desktop.
toggleAttr() jQuery plugin
/*!
* 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);
});
};
@tremby
Copy link

tremby commented Oct 3, 2013

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

@KyleMit
Copy link

KyleMit commented Jan 2, 2015

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.

@victor-rocha
Copy link

victor-rocha commented Jul 13, 2016

$(selector).attr('disabled', function (_, attr) { return !attr });

This works (at least to enable or disable fields) as well!

@ghatolamol
Copy link

@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