I'm Trying to change the background and text color of a table row on click using jQuery and CSS so that only one row may be selected at a time. However I cannot seem to get the CSS to change, even though the class is changing correctly from the jQuery function, so the jQuery appears to be working.
I am very confused why the CSS doesn't change when the class is changed (which I can see happening on the inspect element view on chrome).
Note that the table rows are being generated within a Django template page and the div classes are from Bootstrap.
<div class="row panel panel-default">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Pass #</th>
<th>First Name</th>
<th>Last Name</th>
<th>Type</th>
<th>Active</th>
</tr>
</thead>
<tbody class="member">
{% for member in filter_list %}
{% with member.pass_set.all|first as pass %}
<tr>
<td>{{member.id}}</td>
<td>{{pass.active_id}}</td>
<td>{{member.last_name}}</td>
<td>{{member.first_name}}</td>
<td>{{pass.member_type}}</td>
<td>{{pass.season.is_current|yesno|capfirst}}</td>
</tr>
{% endwith %}
{% endfor %}
</tbody>
</table>
</div>
$("tr").click(function() {
$(this).parent().children().removeClass(".selected");
$(this).addClass(".selected");
});
.member tr:hover {
background-color: rgba(41, 103, 182, 0.89);
color: #FFF;
}
.selected tr{
background-color: rgba(41, 103, 182, 0.89);
color: #FFF;
}
I really thought this would be straight forward, but I have been stuck for a while. Thanks in advance for any help!
Thanks for all the quick responses. I ended up taking advice from all three!
Final solution:
.member tr.selected {
background-color: rgba(41, 103, 182, 0.89);
color: #FFF;
}
$("tbody tr").click(function() {
$(this).addClass('selected').siblings().removeClass("selected");
});
You are adding the selected
class to the tr
element, so your CSS selector is incorrect. You may also want to make it more specific by prefixing it with .member
too. Try this:
.member tr.selected {
background-color: rgba(41, 103, 182, 0.89);
color: #FFF;
}
Also, you may want to amend your jQuery so that only tr
elements within the tbody
can be selected - I doubt you want people to select the heading row:
$("tbody tr").click(function() {
$(this).addClass('selected').siblings().removeClass("selected");
});
Note that there is no .
prefix required for the addClass()
or removeClass()
methods.
Example fiddle
You don't need the .
in the addClass
or removeClass
methods. Likewise you don't need the tr
in your CSS for the .selected
class since you are adding it to a tr
element...
http://jsfiddle.net/2E9T5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With