this is my html code ..in the below code i am having two td's with same background color.so when i click on any of the two td's the background color must be changed using jquery.is it possible to do ????
<table id='main_table' style='width:1002px; border: 1px solid #ccc;'>
<thead>
<tr class='ab'>
<td style='width:500px; background-color:#398bb7; color:white;' onclick=\"Consituteshow('"+cityid+"');\">By Constituency</td>
<td style='width:500px; background-color:#398bb7; color:white;' onclick=\"Partyshow('"+cityid+"');\">By Party</td>
</tr>
</thead>
</table>
Use this keyword
$('#main_table tr.ab td').click(function () {
$(this).css('background-color', '#398bb7');
});
If you want to change background color of both td
$('#main_table tr.ab td').click(function () {
$(this).siblings().add(this).css('background-color', '#398bb7');
});
$('#main_table tr.ab td').click(function () {
$(this).parent().find('td').css('background-color', '#398bb7');
});
Update after OP's comment
use .on()
As your elements are added dynamically so it is not present at the time DOM ready or page load.
So you have to use Event Delegation
Syntax
$( elements ).on( events, selector, data, handler );
js
$(function () {
$(document).on('click', '#main_table td', function () {
$("#main_table tr td").css("background-color", "#398bb7");
$(this).css("background-color", "#FF00FF"); //Add your color
});
});
$(function () {
$(document).on('click', '#main_table td', function () {
$("#main_table tr td").removeClass('active');
$(this).addClass('active');
});
});
css
.active {
background-color:green;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments