Is there any way to do toggle with attributes in jQuery?

3

In JQuery , we have a function called toggle that allows us to switch between the element to be visible or not. And the toggleClass function, which allows you to switch between adding a class or not.

$(function () {
  
  $('button').click(function () { 
    
     $('div').toggle();
    
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divstyle="display:none">Estou aqui</div>

<button>Click</button>

But I have the need to "put and take" an attribute in the same way that this function does. I want to do this with the required attribute in input .

Can you do this in jQuery?

    
asked by anonymous 18.02.2016 / 19:50

2 answers

2

You can create something with jQuery.fn , like this:

jQuery.fn.extend({
  toggleAttribute: function(attr, value) {
    if (typeof value !== "string") {
        value = "true";
    }

    //Pega os elementos que tem o atributo
    var withAttr = this.filter("[" + attr + "]");

    //Pega os elementos sem o atributo
    var noAttr = this.filter(":not([" + attr + "])");

    //Se for classes então não usamos attr, porque classes funcionam diferente
    if (attr === "class") {
        noAttr.addClass(value);
        withAttr.removeClass(value);
    } else {
        noAttr.attr(attr, value);
        withAttr.removeAttr(attr);
    }

    return this;
  }
});

Use this to automatically add required or remove:

$('button').click(function () { 
    $('input').toggleAttribute("required");
});

Use this to automatically add the foo attribute to the value baz or remove:

$('button').click(function () {
    $('div').toggleAttribute("foo", "baz");
});
    
18.02.2016 / 19:57
2

Same as toggle does not, but has .attr () that adds an attribute and .removeAttr () that removes.

    
18.02.2016 / 19:55