views:

78

answers:

3

hello

i have created a table on my application same follwing 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 by click with following jquery code

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

and my css is

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

i would like when i click on a row, other rows be unselected

and just one row be selected

how we could create this?

thanks

+4  A: 
$("tr").click(function(){

 $('tr').removeClass("otherstyle");
 $(this).toggleClass("otherstyle");

}

or

$("tr").click(function(){     

 $(this).toggleClass("otherstyle").siblings().removeClass("otherstyle");

}
Reigel
+6  A: 
$("table.spreadsheet tr").click(function(){
    $("table.spreadsheet tr").removeClass("otherstyle");
    $(this).toggleClass("otherstyle");
});

See a working demo

rahul
+1  A: 

For sake of performance, I'd 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'd be a real kill, but hey, shouldn't we always write fast/optimized code?

dare2be