Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
});
};
@ralfzen

This comment has been minimized.

Copy link

@ralfzen ralfzen commented Feb 22, 2013

thanks for this. i modified this a little for my needs

$.fn.toggleAttr = function(attr, attr1, attr2) {
  return this.each(function() {
    var self = $(this);
    if (self.attr(attr) == attr1)
      self.attr(attr, attr2);
    else
      self.attr(attr, attr1);
  });
};

Usage:

$('a#done').toggleAttr('title', 'Show done Items', 'Hide done Items');
@tremby

This comment has been minimized.

Copy link

@tremby 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

This comment has been minimized.

Copy link

@KyleMit 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

This comment has been minimized.

Copy link

@victor-rocha 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

This comment has been minimized.

Copy link

@ghatolamol ghatolamol commented Nov 30, 2016

@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
You can’t perform that action at this time.