[英]change td background color based on the option value
I want to change the td background color based on the color value selected in dropdown. 我想根据下拉菜单中选择的颜色值更改td背景色。
HTML : 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 : 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. 上面的jquery没有突出显示持有
tdcolor
类的td
元素的背景色。
If someone could help me how to change this using jquery, it would be great. 如果有人可以帮助我如何使用jquery更改此设置,那就太好了。
Many Thanks in advance. 提前谢谢了。
You should use pseudo-class
selector in order to get the selected
text from your dropdown. 您应该使用
pseudo-class
选择器,以便从下拉列表中获取selected
文本。
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 应该是.tdcolor而不是ddcolor
The event should be on select
该事件应处于
select
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.