user3530082
user3530082

Reputation: 37

How to have colors as options in a cell of a table

I know that in a table I can write something like :

<td>
  <select style="width:100%">
    <option value="no">Select</option>
    <option value="yes">Yes</option>
    <option value="no">No</option>
  </select>
</td>

so in that cell I will have a drop down menu, with "Yes" and "No" options.

But I want to have colors as my options, so when a user clicks on a cell, he will see a drop down menu and can see for example red and green colors as options.

I do not know if it is possible to do this and if so, how can I do it?

Upvotes: 0

Views: 150

Answers (1)

nbrooks
nbrooks

Reputation: 18233

Use the CSS background-color property to style the options as red or green:

option[value="green"] {
  background-color: green;
}
option[value="red"] {
  background-color: red;
}
<table style="border: 1px solid lightgray">
  <tr>
    <td>Make Selection
    <td>
      <select style="width:100%">
        <option value="red">Select</option>
        <option value="green">&nbsp;</option>
        <option value="red">&nbsp;</option>
      </select>
    </td>
  </tr>
</table>


If you want to change the style of the select or the td based on the selected option, that's not possible with pure CSS; you'll have to use JavaScript for that. When the value of the select changes, update it's style based on the selected value. The example below uses jQuery, but this is possible in vanilla JS too.

$(function() {
  $("select").change(function() {
    $(this)[0].className = $(this).val();
  });
});
select.green, option[value="green"] { background-color: green; }
select.red, option[value="red"] { background-color: red; }
select option { background-color: lightgray; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<td>
  <select style="width:130px">
    <option>Select</option>
    <option value="green">&nbsp;</option>
    <option value="red">&nbsp;</option>
  </select>
</td>

Upvotes: 2

Related Questions