Bas
Bas

Reputation: 2210

jQuery add class and remove it for all the elements who doesnt have it

I'm trying to make a system, to make the user select a table row by itself, then press the delete button to delete it.

So i made this:

$("#container tbody tr").click(function () {
    $(this).addClass("selectedRow");
});

function delete() {
    var check = confirm("Are you sure you want to delete this?");
    if (check) {
         $(".selectedRow").remove();
    }
}

$("#delete-btn").click(delete);

And for the CSS:

#container tbody tr.selectedRow {
   background-color: red; 
}

So i'm trying to achieve, when i click a table row inside the tbody that it gives the selectedRow class to it, but it removes the class of any other element in that same container.

How do i make it so that i can only select one tr (table row)?

My own try:

$("#container tbody tr").click(function () {
    $(this).addClass("selectedRow");
    $(this).parent().removeClass("selectedRow");
});

But that didnt work

Upvotes: 1

Views: 1125

Answers (6)

J Prakash
J Prakash

Reputation: 1333

$("#container tbody tr").click(function () {

 // Remove selectedRow class from any rows having it in this table
 $(".selectedRow").removeClass("selectedRow");

 // Add it to the clicked row
 $(this).addClass("selectedRow");

});

Upvotes: 0

RGS
RGS

Reputation: 5211

$("#container tbody tr").click(function () {
    $(this).addClass("selectedRow").siblings().removeClass("selectedRow");

});

Upvotes: 0

Valentin Mercier
Valentin Mercier

Reputation: 5326

Edit your managing function to this:

$("#container tbody tr").click(function () {
    $(this).parent().find(".selectedRow").removeClass("selectedRow");
    $(this).addClass("selectedRow");
});

Upvotes: 1

techfoobar
techfoobar

Reputation: 66673

You can use:

$("#container tbody tr").click(function () {

    // Remove selectedRow class from any rows having it in this table
    $('.selectedRow', $(this).parent()).removeClass("selectedRow");

    // Add it to the clicked row
    $(this).addClass("selectedRow");

});

Upvotes: 2

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Do like this

$("#container tbody tr").click(function () {
    $(".selectedRow").removeClass("selectedRow");
    $(this).addClass("selectedRow");

});

First line will remove the class name of selectedRow from all elements. Then you can add the class to clicked element.

Upvotes: 3

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Do you mean like this?

$("#container tbody tr").click(function () {
    $(this).parent().find(".selectedRow").removeClass("selectedRow");
    $(this).addClass("selectedRow");
});

Upvotes: 1

Related Questions