In jQuery gibt es die Funktionen „toggle“ um Elemente ein/auszublenden und „toggleClass“ um zwischen 2 CSS-Klassen hin und her zu wechseln. Da liegt es doch nahe diese Funktion auch für sämtliche HTML-Attribute umzusetzen. Ich brauchte diese Funktion um komfortabel via Button ein Passwortfeld zu einem normalen Feld zu switchen.
(function ( $ ) {
$.fn.toggleAttr = function(attr, value) {
if (!this.data('old-attr')) this.data('old-attr', this.attr(attr));
if (!this.data('new-attr')) this.data('new-attr', value);
if (!this.data('toggle-attr')) this.data('toggle-attr', attr);
if (this.attr(attr) == value) this.attr(attr, this.data('old-attr'));
else this.attr(attr, value);
return this;
};
}( jQuery ));
Anwendungsbeispiel:
<input placeholder="Passwort" type="password" />
<button type="button" onclick="$(this).prev('input').toggleAttr('type','text')">
show/hide pass
</button>
Den Code findet ihr auch auf GitHub.