A componentized solution (i.e., it can be encapsulated), is possible using jQuery and css classes:
$("#mytable > tbody > tr").on("click", function (e) {
$(this).siblings().removeClass("ativo");
$(this).toggleClass("ativo");
});
CSS:
.ativo {
background-color: #00F;
color: white;
}
Selecting a specific table, and the specific Rows
The selector in the root table (i.e. #mytable
), allows you to place other tables on the page without affecting them. As well as operator use >
to get to Row. This allows componentizing the solution.
Why use siblings to remove the active class?
Also, remove the class ativo
through the siblings
, leaves the solution well encapsulated to the desired table. You could have subtabels inside the table, and still it would work.
The tbody
in the middle serves to select body only Rows, footer or header.
EDIT
You can use a style user-select: none
so that quick clicks on the same line do not end up selecting the text.
And also a cursor: pointer
to indicate that the user can click there.
EDIT
To get into the performance merit, and keep the code legible, I’ll just say one thing...
until someone gets over it
$("#mytable > tbody > tr").on("click", function (e) {
var $this = $(this);
// bem... esse não é o lugar mais recomendável para armazenar o cache, ou é?
this.$siblings = this.$siblings || $this.siblings();
this.$siblings.removeClass("ativo");
$this.toggleClass("ativo");
});
You want to change the selected lines at each click or select and deselect just by clicking on the home line (in the second case several lines may be selected at the same time, in the first no)
– Erlon Charles