I am creating an element on a website in which the user will be able to update the status of a job/order.
The best way that I found to make this work is by creating a drop down list and then styling it.
HTML
<select name="status" id="status">
<option value="Completed">Completed</option>
<option value="Incomplete">Incomplete</option>
</select>
CSS
#status {
width: 100px;
height: 20px;
background-color: green;
color: lightgreen;
font-size: 18px;
text-align: center;
}
While this all works well, my main issue is that I would like the background and font colour of the actual select box to change depending on the option selected. I.e, if "Incomplete" was to be selected "background-color" would change to "orange" and "color" would change to "lightcoral".
6
Answers
You have to use a little javascript to do it, maybe the simplest way is to add a class for complete and not complete state, here is an example
It only reacts when you change de value, you could do more adding an empty state, a pre selected value, you can customize it… this is just an example of how to toggle classes.
Good luck!
You will need to use JavaScript to listen for the change event on the select element and update the styling accordingly.
May be try something like this:
the CSS:
Then the javascript:
This should work:
EDIT:
I wrote #status instead of the option tag.
NOTE
This is gonna change EVERY option that is selected on the page, to make it change only in that select you have to do like this:
You need js logic to change style based on selected value.
Example:
Using Javascript, attaching a change event listener to the dropdown and evaluating the value to change styling will work. Below is a way of pre-defining the CSS styles by class names. This would also make it easier if you wanted to add more options to the dropdown or if the dropdown style grows.
I also added a prompt option with no value as a default style. Needed, probably not but left it in as an alternative.
With just CSS you can style it with
has()
and:checked