I want to change the td background color based on the color value selected in dropdown.
HTML :
<table border="1">
<tr>
<th>Channel</th>
<th>Health</th>
</tr>
<tr>
<td>Mobile</td>
<td class="tdcolor">
<select >
<option value="0">Select</option>
<option value="1">Green</option>
<option value="2">Red</option>
<option value="3">Amber</option>
</select>
</td>
</tr>
</table>
jquery :
$(document).ready(function(){
$('td.tdcolor').change( function() {
$(this).css('background-color','green');
});
});
The above jquery is not highlighting the background color of td
element holding tdcolor
class.
If someone could help me how to change this using jquery, it would be great.
Many Thanks in advance.
You should use pseudo-class
selector in order to get the selected
text from your dropdown.
var text = $(this).find(':selected').text();
$(document).ready(function(){ $('td.tdcolor').change( function() { $(this).css('background-color',$(this).find(':selected').text()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table border="1"> <tr> <th>Channel</th> <th>Health</th> </tr> <tr> <td>Mobile</td> <td class="tdcolor"> <select > <option value="0">Select</option> <option value="1">Green</option> <option value="2">Red</option> <option value="3">Blue</option> </select> </td> </tr> </table>
$(document).ready(function() { $('#color').change(function() {//add an id to html and use as selector $(this).parent("td").css('background-color', $('option:selected', this).text());//use the text of selected option as parameter }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table border="1"> <tr> <th>Channel</th> <th>Health</th> </tr> <tr> <td>Mobile</td> <td class="tdcolor"> <select id='color'> <option value="0">Select</option> <option value="1">Green</option> <option value="2">Red</option> <option value="3">Amber</option> </select> </td> </tr> </table>
$(document).ready(function(){
$('select').change( function() {
$(".tdcolor").css('background-color','green');
});
});
Should be .tdcolor not ddcolor
The event should be on select
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.