If I have a selector with drop-down options, how can I change a color of all cells in this row on change?
function changeColor(){
}
$(".mySelector").change(function() {
changeColor();
});
<table>
<tr>
<td>val 1</td>
<td>val 2</td>
<td>
<select class="mySelector">
<option value="red">red</option>
<option value="grn">green</option>
<option value="blu">blue</option>
</select>
</td>
</tr>
<tr>
<td>val 3</td>
<td>val 4</td>
<td>
<select class="mySelector">
<option value="red">red</option>
<option value="grn">green</option>
开发者_开发问答 <option value="blu">blue</option>
</select>
</td>
</tr>
</table>
You can use closest() to get the nearest <tr>
ancestor of your <select>
element:
$(".mySelector").change(function() {
$(this).closest("tr").css("background-color",
$("option:selected", this).text());
});
You should change your option values to valid colors instead of abbreviations, then you can do this:
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
JS:
$(".mySelector").change(function() {
$(this).closest("tr").css("background-color", this.value);
});
JSFiddle: http://jsfiddle.net/A2FFT/
If you want to make sure the color gets set on initialization, you can chain another change
call to it.:
$(".mySelector").change(function() {
$(this).closest("tr").css("background-color", this.value);
}).change(); //Set background color without needing to change the selected option.
精彩评论