Reputation: 2210
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
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
Reputation: 5211
$("#container tbody tr").click(function () {
$(this).addClass("selectedRow").siblings().removeClass("selectedRow");
});
Upvotes: 0
Reputation: 5326
Edit your managing function to this:
$("#container tbody tr").click(function () {
$(this).parent().find(".selectedRow").removeClass("selectedRow");
$(this).addClass("selectedRow");
});
Upvotes: 1
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
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
Reputation: 26143
Do you mean like this?
$("#container tbody tr").click(function () {
$(this).parent().find(".selectedRow").removeClass("selectedRow");
$(this).addClass("selectedRow");
});
Upvotes: 1