1 <...">

How to select only table row using jQuery

I created a table in my application, the same as the code

<table class="spreadsheet"> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> </tr> </table> 

I select a row with a click with the following jQuery code

  $("tr").click(function(){ $(this).toggleClass("otherstyle"); } 

and my css

 tr.otherstyle td { background-color: #d1db3e; color:#000; } 

I would like when I click on a row, no other rows are selected and only one row is selected.

How could we create this?

+4
source share
3 answers
 $("table.spreadsheet tr").click(function(){ $("table.spreadsheet tr").removeClass("otherstyle"); $(this).toggleClass("otherstyle"); }); 

See a working demo

+8
source
 $("tr").click(function(){ $('tr').removeClass("otherstyle"); $(this).toggleClass("otherstyle"); } 

or

 $("tr").click(function(){ $(this).toggleClass("otherstyle").siblings().removeClass("otherstyle"); } 
+5
source

For better performance, I would change rahul's answer to

 $("table.spreadsheet tr").click(function(){ $("table.spreadsheet tr").removeClass("otherstyle"); $(this).addClass("otherstyle"); // avoid checking if it has the class "otherstyle" // because it does not }); 

Not that it was a real kill, but hey, shouldn't we always write fast / optimized code?

+2
source

Source: https://habr.com/ru/post/1308327/


All Articles