How to mark and unmark a row from a table by clicking on it?

Asked

Viewed 10,769 times

11

When clicking on a row of a table, how to mark it by changing the color of the row background, and if you click again uncheck the background, and if you click on another row uncheck the old checked and mark the new.

How to do this using Javascript / jQuery?

  • 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)

5 answers

11


You can use it like this:

To apply across the board can use $('table tr');

var tr = $('table tr:not(:first-child)');  // o :not(:first-child) é util no meu exemplo somente porque usa th
tr.on('click', function () {
    tr.not(this).removeClass('colorir');
    $(this).toggleClass('colorir');
});

Example

I leave one more variant slightly faster code.
I took a test (link) and this second option is even the fastest.

Code:

var tr = $('table tr:not(:first-child)');
tr.on('click', function () {
    var self = this;
    tr.each(function(){
        if(this == self) $(this).toggleClass('colorir');
        else $(this).removeClass('colorir');
    })
});

Exemplo2


To apply in each cell can use $('table td');

var td = $('table td');          // pôr todas as td em cache
td.on('click', function () {     // agregar um event handler para executar aquando um click
    td.not(this).removeClass('colorir');   // remover a classe em todas as td menos a que recebeu click
    $(this).toggleClass('colorir'); // adicionar/remover a classe àquela que foi clicada
});

Example


CSS is the same for both options:

.colorir {
    background-color:#fcc;
}
  • @luiscubal, I was editing

  • Yes, now it’s right. By the way, if you click on the title, it de-selects all lines. Is it intentional? If not, you can use the selector :not(:first-child)

  • @luiscubal, good observation! I added this to the reply. Thank you.

8

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.

Example in jsfiddle

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...

Most performatic example of all =)

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");
});
  • +1. It is the simplest, most complete and fastest answer. Here’s a fiddle that demonstrates full functionality using this solution: http://jsfiddle.net/ZGKrK/4/

  • @Spark, I ran a test because I wasn’t sure: http://jsperf.com/html-table-toggle

  • Actually, this solution is only good up to 39 clicks per second, while the other solutions are much better and support up to 115 clicks per second. =)

  • hmm... in jsperf you reversed the name of the tests not and each, but it gave an idea

  • I also made a jsperf just to play a little: http://jsperf.com/html-table-toggle-with-cache

2

You will have to add a class named on the first click active à tr and from there to each click check whether the tr possesses the class, if you own you remove, if you do not add.

Example:

$("tr").on('click', function () {
    if($(this).hasClass("active")) {
        $(this).removeClass("active");
    } else {
        $(this).addClass("active");
    }
});

And define the of that class.

Example:

tr.active {
    background-color: yelow;
}

You can see an example here

This way each click will select or remove the selection from a row.

2

I didn’t see anyone meet the requirement of the question, so follow my version:

$('#codexpl').on('click', 'tr', function () {
    $(this).siblings().removeClass('marcada');
    $(this).toggleClass('marcada');
});

It allows you to select one line at a time, and when you click again on the marked line, you lose the marking.

Jsfiddle

Note: the fiddle was a Fork based on the @Sergio version

  • 1

    I realized a little... hehe

1

Or you can use a global variable to store the selected object.

$('<tr>').click(function () {
    objMarcado = this;
    $(this).addClass('colorir');
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.