Reputation: 704
I have a table displayed in HTML which has two kinds of class
1 - alt 2 - SelectedrowData
initially the will have class "alt" when clicked the class will be changed to "SelectedrowData". At the same time remaining whose class was "SelectedrowData" should to be retained to "alt".
In simple words. When I click on a row the class name should be toggled. Same follows when I click on other rows. In fact in the whole table there will be only 1 "SelectedrowData"
My table is as below
<table>
<thead></thead>
<tbody>
<tr class="alt">
<td>72</td>
<td>SALES DEPT. SALES STAFF</td>
<td class="fieldHide">7018072</td>
<td class="fieldHide">7018572</td>
<td class="fieldHide">7018072</td>
<td class="fieldHide">7018072</td>
<td class="fieldHide">6</td>
<td class="fieldHide"></td>
<td>Default</td>
</tr>
<tr class="SelectedrowData">
<td>73</td>
<td>SALES DEPT. OFFICE ADMIN</td>
<td class="fieldHide">7018073</td>
<td class="fieldHide">7018573</td>
<td class="fieldHide">7018073</td>
<td class="fieldHide">7018073</td>
<td class="fieldHide">7</td>
<td class="fieldHide"></td>
<td>Default</td>
</tr>
<tr class="alt">
<td>72</td>
<td>SALES</td>
<td class="fieldHide">7018072</td>
<td class="fieldHide">7018572</td>
<td class="fieldHide">7018072</td>
<td class="fieldHide">7018072</td>
<td class="fieldHide">6</td>
<td class="fieldHide"></td>
<td>Default</td>
</tr>
</tbody>
</table>
Upvotes: 2
Views: 149
Reputation: 144709
$('tr').click(function(){
$(this).attr('class', 'SelectedrowData')
.siblings().attr('class', 'alt');
});
Upvotes: 3
Reputation: 791
You can try this
$('table').click(function(e){
var $clickedRow;
if(e.target.nodeName === 'TR') {
$clickedRow = $(e.target);
} else {
if($(e.target).parents('tr').length > 0) {
$clickedRow = $(e.target).parents('tr');
} else {
$clickedRow = undefined;
}
}
if($clickedRow) {
$('.SelectedrowData').removeClass('SelectedrowData');
$clickedRow.removeClass('alt').addClass('SelectedrowData');
}
});
This will handle clicks on both tr and td.
Upvotes: 0
Reputation: 318302
If it's the whole table, just do:
$('tr').on('click', function() {
$(".SelectedrowData").add(this).toggleClass('alt SelectedrowData');
});
Upvotes: 0
Reputation: 1719
$('tbody tr').click(function(){
// First, make all the tr's have the 'alt' class
$('tbody tr').attr('class','alt');
// Now make this tr the one with the unique class
$(this).attr('class', 'SelectedrowData');
});
Upvotes: 0