Reputation: 20078
How can I change the background color only to those rows that clicked, in the below code it does not clear the previous row clicked background color.
var tr = $('#webgrid_id').find('tr');
tr.bind('click', function (event) {
$("tr").click(function () { $(this).css('background', 'yellow'); });
});
Upvotes: 1
Views: 945
Reputation: 2180
try below code
var tr = $('#webgrid_id').find('tr');
tr.bind('click', function (event) {
tr.css('background','');
$("tr").click(function () {
$(this).css('background', 'yellow');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="webgrid_id">
<tbody>
<tr>
<td>a</td>
</tr>
<tr>
<td>b</td>
</tr>
<tr>
<td>c</td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 20636
You could simplify it by using class
.yellow{
background: yellow;
}
Add the above to <style>
or CSS file
$('#webgrid_id').on('click','tr',function () {
$('tr.yellow').removeClass('yellow');
$(this).addClass('yellow');
});
OR as @A. Wolff suggests refer this (more optimized and improved): http://jsfiddle.net/12mze843/1/
Also, I see a click
event inside bind - there is no need to nesting these events.
Upvotes: 7
Reputation: 1
var tr = $('#webgrid_id').find('tr');
tr.bind('click', function(event) {
$(this).css('background', 'yellow')
.siblings("tr").css('background', '#fff');
});
tr td {
font-size: 48px;
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<table id="webgrid_id">
<tbody>
<tr>
<td>a</td>
</tr>
<tr>
<td>b</td>
</tr>
<tr>
<td>c</td>
</tr>
</tbody>
</table>
Upvotes: 3
Reputation: 8291
Here is a demo: https://jsfiddle.net/erkaner/4mf61j5s/1/
$('body').on('click', 'tr', function (event) {
$('#webgrid_id tr').removeClass('clickedrow');//clear all highlights
$(this).toggleClass('clickedrow');
});
And you need to have this style:
<style>
.clickedrow {background-color:yellow;}
</style>
Upvotes: 1
Reputation:
Just give a class to it and change this class when clicking
$("head").append("<style type='text/css'>.inYellow{background-color:yellow;}</style>");
$("tr").on("click", function(){
$(this).toggleClass("inYellow");
});
Upvotes: 1
Reputation: 1121
You could save the previously clicked row in a variable and change it's back color to the old color when another row is clicked, like this:
var prevTr = null;
var tr = $('#webgrid_id').find('tr');
prevTr = tr;
tr.bind('click', function (event) {
$("tr").click(function () {
$(this).css('background', 'yellow');
$(prevTr).css('background', 'white');
});
});
Upvotes: 1