Toggle text and class of a link when clicked - jQuery

Asked

Viewed 463 times

5

I’m trying to make the delegation an event click There is a link within a table, how this jsFiddle example shows:

The result obtained as you can see, is:

  • By clicking on the link "Activate", the event click assigned to the class .activate is fired, thus changing the class of the same link to .deactivate.
  • By clicking on the link "Deactivate", the event click assigned to the class .activate is fired again but nothing happening, and the correct would be the execution of the event click changing again its class to .activate.

For a better understanding, please open the link to jsFiddle.

Taking some examples that I had already done, and researching cases similar to mine, I discovered that I should delegate the event as follows:

$(document).on("click", "#element", function (e) {});

However I did not get the expected result, as you can see in this other jsFiddle example.
I am available to add further information if necessary.

2 answers

5


I think it would be best to do this in one function using one if/else and pointing the click to a class (that in this case could not be a id as this will be used more than once) that is not modified due to user interactions to avoid conflicts, as in this example below:

$('.status').click(function() {
    if ($(this).hasClass('ativar')) {
        $(this).removeClass('ativar').addClass('desativar').text('Ativar');
    }
    else {
        $(this).removeClass('desativar').addClass('ativar').text('Desativar');
    }
});
th,td {
    border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="content">
    <table>
        <thead>
            <tr>
                <th>Titulo 1</th>
                <th>Titulo 2</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Campo 1</td>
                <td>Campo 2</td>
                <td><a href="#" class="status">Ativar</a></td>
            </tr>
            <tr>
                <td>Campo 3</td>
                <td>Campo 4</td>
                <td><a href="#" class="status">Ativar</a></td>
            </tr>
        </tbody>
    </table>
</div>

  • 1

    Thank you very much, it worked perfectly for me!

5

Your code was right! You just forgot to join jQuery in jsFiddle.

If you want to compress the code further you can do so:

$('.content tbody').on("click", ".activate, .deactivate", function (e) {
    e.preventDefault();
    var ativo = $(this).hasClass('activate');
    $(this).html(ativo ? "Desativar" : "Ativar").toggleClass("activate deactivate");
});

Example: http://jsfiddle.net/am2h9149/

  • 2

    Our! an even simpler solution, thank you very much! It will surely be of great use. :)

Browser other questions tagged

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