What is the best way to style the currently selected option element in a select dropdown?

I am trying to change the font color of specific option elements within a select dropdown by adding style="color: #D4D4D4". When I apply this style directly to an option element like

<option value="TEST" style="color: #D4D4D4">TEST</option>
, it works when the options are expanded. However, the selected option (when the dropdown is closed) still shows the default font color. How can I change this as well?

Update:

Thank you for the suggestion! Unfortunately, using sel.onchange does not track attribute changes made to option elements. I am using jQuery to set attributes and need the updates to be immediately reflected in the select dropdown. Is there a way to achieve this?

Here is my jQuery code:

$('.form-control option[value="' + $scope.environment + '"]').attr('style', 'color: #D4D4D4');

Answer №1

var selectElement = document.getElementById("select-element");

function changeSelectColor(){
  selectElement.style.color = selectElement.options[selectElement.selectedIndex].style.color;
}

changeSelectColor(); // Execute once ready
selectElement.onchange = changeSelectColor; // Trigger on change event
<select id="select-element">
    <option value="TEST1" style="color:red">TEST1</option>
    <option value="TEST2" style="color:blue">TEST2</option>
    <option value="TEST3" style="color:green">TEST3</option>
</select>

Answer №2

Use this code snippet to achieve the desired effect

JAVASCRIPT

    $('#selectElement').change(function(){
        $('#selectElement').find(":selected").css('color', '#D4D4D4');
        $('#selectElement').find("option:not(:selected)").css('color', '#000000');
    });

See an example here: http://example.com/12345

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send dropdown selections to a Javascript function and convert them into an array

Within my JavaScript function, I need to pass multiple selected values from dropdown menus and store them in a JavaScript array. Each time a value is selected and sent using the onchange() function, it should be added to the array. If the same value is sel ...

iPhone Safari Mobile Browser experiencing issues with sms: and mailto: functionalities

Issue: Encountering a problem with web pages containing sms: and mailto: links not functioning on iOS mobile Safari browser. Clicking on the link redirects to: Safari cannot open the page because it cannot redirect to locations starting with "sms:& ...

The protected routes within a React JS application consistently result in an undefined value

In my ProtectedRoute component for my react application, I am facing an issue with user authentication. I am using react-router-dom v6 to access the token from localStorage, but no matter what, the user variable always returns undefined. import { Outlet, N ...

The information I input into this form is failing to be stored in the WAMP database

After implementing this PHP code, there are no error messages being displayed when I submit the HTML form. However, the data is not being added to the WAMP table. <?php error_reporting(E_ALL); ini_set('display_errors', 1); //$user_name = "roo ...

Disregarding 'zIndex' directive within JavaScript function, an image stands apart

There is an issue with the z-index values of rows of images on my webpage. Normally, the z-index values increase as you scroll further down the page. However, I want certain items to have a lower z-index than the rest (except on hover). These items are i ...

Choose the element before and add a style effect with CSS

I'm trying to create a layout with 3 <div> elements in one horizontal line, each with a width of 33.33%. When hovering over one div, I want its width to expand to 50% while the other two shrink to 25%. <div id="A"></div> <div id= ...

Is there a way to refine a table based on the specific rows that are chosen in ag-Grid?

Is it possible to filter a table by rows with the attribute select: true, considering that select is not part of the data but rather an attribute of RowNode? I have tried using gridApi.getSelectedNodes() as well as text and number filters, but haven' ...

What are the steps to adjust the width of a website from the standard size to a widescreen

Is it possible to create a "floating" screen adjustment on websites? I know you can set the standard size of pixels, but how do sites adjust for different screen sizes like wider laptop screens? Does it automatically detect the reader's screen size an ...

Enhance the appearance of Ionic popups

Can someone help me with resizing a pop up? I've been struggling to get it right. This is the popup template in question: <ion-view> <ion-content scroll="false" class=""> test </ion-content> < ...

Approach for fetching these JSON records

I am currently exploring ways to retrieve all entries within a JSON payload using JavaScript. Specifically, I am interested in finding the best method to extract all instances of "o4" in a specific order (-159, -257). How can this be achieved? { ...

Is the new mui LoadingButton not available in the latest version?

According to the material UI documentation found at here, you are supposed to import LoadingButton from '@material-ui/lab/LoadingButton'; However, I am unable to locate this folder within mui/lab and the import statement is resulting in an erro ...

Pictures failing to load on both Chrome and Safari browsers

For some reason, the images on my app are not appearing in Chrome and Safari but show up fine in Firefox. If you try to open the image URL in a browser, it works perfectly. However, when embedded in the HTML document, the image appears broken. I also test ...

Can we expect React's useState to wait before executing subsequent logic, or will it immediately update the state and trigger a re-render

I have a specific scenario in my code where I am using the useState setter function in React to update a value on line 5. Everything seems to be functioning well without any errors, but I'm curious about something. Since setState updates the state and ...

Utilize Bootstrap button dropdown to automatically assign a selected value to a list item

I have a form with a select box that transforms into a bootstrap button after the page loads. However, I am unable to set the selected value for the converted bootstrap button drop-down li. <button type="button" class="btn dropdown-toggle btn-default" ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

React Intersection Observer not functioning properly

Hey there! I'm trying to create an animation where the title slides down and the left element slides to the right when scrolling, using the intersection observer. Everything seems to be fine in my code, but for some reason it's not working. Any t ...

Retrieving a specific view by utilizing the primary key in the URL pattern

Greetings. I am facing some difficulties in retrieving the URL with the passed argument (pk). An error occurs where I receive post_edit, which is related to another application on the website. Here is the error message: NoReverseMatch at /questions/questi ...

AngularJS dual-stage resolution for resolving dependencies

I am facing a scenario where I must resolve one item before obtaining the data necessary to resolve another: .state('addtrip', { url: '/addtrip', templateUrl: 'views/addtrip.html', controller: &a ...

What is the best way to distinguish between inline javascript and dynamically created content in Express/Node.js?

I've encountered a bit of a noob-question despite having a few years of experience in web development. Despite searching Programmer Stack Exchange and Google, I haven't found an answer, so here goes. Currently, I'm working with the Express ...

The ng-repeat directive adds an additional line after each iteration of the list item

Whenever the angular directive ng-repeat is utilized with an <li> element, I notice an additional line appearing after each <li>. To demonstrate this issue, see the simple example below along with corresponding images. Here is a basic example ...