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.
**Solution **
<style>
select {
color: #b8b8b8;
background-color: #333; /* Optional: Set a background color for better contrast */
}
select.valid {
color: #fff;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form>
<select id="mySelect">
<option selected disabled>please select</option>
<option>Yes</option>
<option>No</option>
</select>
</form>
<script>
$(document).ready(function() {
$('#mySelect').on('change', function() {
if ($(this).val() !== 'please select') {
$(this).addClass('valid');
} else {
$(this).removeClass('valid');
}
});
});
</script>
</body>