I want to style the text color in the select field as gray (#b8b8b8), and when a selection (either Yes or NO) is made, the select field text should be styled as white (#fff).
<form>
<select>
<option selected disabled>please select</option>
<option>Yes</option>
<option>No</option>
</select>
</form>
I tried all jquery solutions I could find on Stackoverflow, but none of those solutions apply to my needs. I tried using togglefields, but that styles ALL the text in the options, not the select field.
EDIT:
This is the last solution I tried:
function myFunction() {
document.getElementById("myform").reset();
}
$(document).ready(function() {
$("#selection").change(toggleFields);
});
function toggleFields() {
if ($("#selection").val() == "none") {
$("#selection").css("color", "blue");
} else {
$("#selection").css("color", "red");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form id="myform">
<select id="selection">
<option value="none" selected disabled>please select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</form>
As you can see, it styles the "yes" and "no" options as red, but it doesn’t style the "please select" option as blue. I also tried to target the disabled
option directly with css, but that only changed the dropdown <option>
styling when the list is open (dropped down), not the styling when the dropdown is initially closed upon loading of the page.
2
Answers
Your code is correct, it’s just not working because any select option doesn’t have a
none
value.So add a
none
value to the select option and it will work fine.To achieve the same on page load, call the function
toggleFields()
directly.working snippet:
**Solution **