Toggle text and class of a link when clicked - jQuery

5

I'm trying to delegate a click event to a link inside a table, as this jsFiddle sample shows :

The result you can see is:

  • By clicking the " Enable " link, the click event assigned to the .activate class is triggered, thereby changing the class of the same link to .deactivate .
  • By clicking on the " Disable " link, the click event assigned to the .activate class is fired again but nothing happens, and the correct execution of the click event is changed again its class to .activate .

For a better understanding, please open the jsFiddle link.

Taking some examples that I had already done, and searching for 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 sample . I am available to add more information if needed.

    
asked by anonymous 15.10.2015 / 06:04

2 answers

5

I think it would be best to do this in a single function using a if/else and pointing the click to a class (which in this case could not be a id since this will be used more than once) than 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><divclass="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>
    
15.10.2015 / 06:49
5

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

If you want to compress the code even more, you can do this:

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

Example: link

    
15.10.2015 / 07:39