AmazingDayToday
AmazingDayToday

Reputation: 4272

jQuery: Issue with if

$("#test > div > div.row-fluid > table > tbody > tr > td:nth-child(3)").after("<td><i class='fa fa-plus-square-o'></i></td>");

$("#test > div > div.row-fluid > table > tbody > tr > td:nth-child(4)").click(function()
{
    if ($("#test > div > div.row-fluid > table > tbody > tr > td:nth-child(4) > i").hasClass("fa fa-plus-square-o")){
        $(this).replaceWith("<td><i class='fa fa-minus-square-o'></i></td>");
    }
    if ($("#test > div > div.row-fluid > table > tbody > tr > td:nth-child(4) > i").hasClass("fa fa-minus-square-o")){
        $(this).replaceWith("<td><i class='fa fa-plus-square-o'></i></td>");
    }
});

This is the code I have. First if works, but after it has changed, but second if doesn't work if I want to change it back.

Thanks!

Upvotes: 1

Views: 37

Answers (3)

DinoMyte
DinoMyte

Reputation: 8858

Try this :

$(document).on("click","#test > div > div.row-fluid > table > tbody > tr > td:nth-child(4) > i",function()
{
    $(this).toggleClass("fa-minus-square-o fa-plus-square-o");
});

Upvotes: 0

Rens Tillmann
Rens Tillmann

Reputation: 861

Use document statement on events, after changing content it cannot determine new classes this way.

But a better way to achieve it is by doing this:

if($('#test etc..').hasClass('fa-minus-square-o')){
    $(this).attr('class', 'fa fa-plus-square-o');
    // or toggleClass
}

Upvotes: 0

BenG
BenG

Reputation: 15154

If you are just trying to change the class on the i, try toggle:-

$("#test > div > div.row-fluid > table > tbody > tr > td:nth-child(4)").click(function()
{
    $('i', this).toggleClass('fa-plus-square-o fa-minus-square-o');
});

Upvotes: 1

Related Questions