Is there any way to toggle with attributes in jQuery?

Asked

Viewed 124 times

3

In the JQuery, we have a function called toggle which allows us to switch between the element being visible or not. And the function toggleClass, which toggles between whether or not to include a class.

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

<div style="display:none">Estou aqui</div>

<button>Click</button>

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

You can do it in jQuery?

2 answers

2

Just like toggle doesn’t, but it has the .attr() adding an attribute and the .removeAttr() that removes.

2


Can create something with jQuery.fn, thus:

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;
  }
});

The use stays like this to automatically add required or remove:

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

The use is thus to automatically add the attribute foo with the value baz or remove:

$('button').click(function () {
    $('div').toggleAttribute("foo", "baz");
});
  • 1

    Pènsei right there, boss, but in a way that would work for any attribute. Anyway +1 ;)

  • @Wallacedesouza already corrected... because it is ... for me win upvotes guys come by wagon (this when I win, because it turned rarity), to me Win downvote the guys see rocket...

  • They took and put the vote (strip and put several times). I think someone is joking because the question is just about toggle. Rsrsrsrsrsrs

  • 1

    @Wallacedesouza was a jQuery extension called toggleHater.js, works like this $("@guilhermenascimento").toggleHater();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.