How can I use JavaScript to alter the background color of a dropdown option when selecting a different option?

Below is the code snippet for a dropdown menu:

 <select name="sourcesSelect" id="{{this.commonID}}" class="custom-select sources" data-color="" placeholder="{{this.status}}">
      <option value="0">In Progress</option>
      <option value="1">Done</option>
      <option value="2">Rejected</option>
    </select>

The default CSS style for this select menu is as follows:

.custom-select-trigger {
    position: relative;
    display: block;
    width: 280px;
    padding: 0 64px 0 20px;
    font-size: 16px;
    font-weight: 300;
    color: #fff;
    line-height: 30px;
    background: #265a88;
    border-radius: 4px;
    cursor: pointer;
  }

Requirement: Change the dropdown color to green when option 0 is selected, red for option 1, and yellow for option 2.

How can this be accomplished?

Dynamic application of CSS on the dropdown menu:

$(".custom-select").each(function() {
var classes = $(this).attr("class"),
    id      = $(this).attr("id"),
    name    = $(this).attr("name");

var template =  '<div class="' + classes + '">';
    template += '<span class="custom-select-trigger">' + $(this).attr("placeholder") + '</span>';
    template += '<div class="custom-options">';
    $(this).find("option").each(function() {
      template += '<span class="custom-option ' + $(this).attr("class") + '" data-value="' + $(this).attr("value") + '">' + $(this).html() + '</span>';
    });
template += '</div></div>';

$(this).wrap('<div class="custom-select-wrapper"></div>');
$(this).hide();
$(this).after(template);
});

$(".custom-option:first-of-type").hover(function() {
$(this).parents(".custom-options").addClass("option-hover");
}, function() {
$(this).parents(".custom-options").removeClass("option-hover");
});

$(".custom-select-trigger").on("click", function() {
$('html').one('click',function() {
  $(".custom-select").removeClass("opened");
});

$(this).parents(".custom-select").toggleClass("opened");
event.stopPropagation();
});

$(".custom-option").on("click", function() {
  $.LoadingOverlay("show");

$(this).parents(".custom-select-wrapper").find("select").val($(this).data("value"));
var id = $(this).parents(".custom-select-wrapper").find("select").attr("id");
var placeholder = $(this).parents(".custom-select-wrapper").find("select").attr("placeholder");
$(this).parents(".custom-options").find(".custom-option").removeClass("selection");
 // alert(placeholder);
$(this).addClass("selection");
$(this).parents(".custom-select").removeClass("opened");
$(this).parents(".custom-select").find(".custom-select-trigger").text($(this).text());

Answer №1

To enhance customization, consider assigning unique classes or IDs to each option element, allowing for targeted styling in CSS. For example:

<option value = "0" class = "option_0"> ---Content---</option>

You can then apply styles based on user interaction, such as changing the background color on hover:

.option_0:hover{background: red;}

Similarly, you can adjust styles for click events by using:

.option_0:active{background: red;}

Repeat this process for each option to achieve a cohesive and personalized design.

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

The dependency graph of npm modules shows significant differences

I've been exploring the capabilities of the npm-remote-ls package to analyze dependency trees for modules. This tool is installed globally on my system. When I execute Command 1: npm-remote-ls object-assign The tree structure displayed is as follows ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...

Why doesn't "align-self: flex-end" relocate the game board to the bottom of the screen?

Hey there, I am currently working on developing a Connect 4 game and have decided to use a table for the board. To position the board properly, I am utilizing flexbox. Although I have specified align-items as 'flex-end' in order to bring it to th ...

Utilizing template engines for sending plain text emails in Node.js

MsSQL - 2014 Recently delving into the world of Node.js programming. I have stored email templates in a database table. For example: message1 : Hello {friendName}, Happy Birthday {friendName}. Thank you, ...

What are the steps to launch a Node.js server on a web server?

I have initiated my personal project, utilizing the following technologies: Front end - Angular JS Back end - MongoDB Server Layer - Node.js I have made some progress on my local system. To run the server on my local system, I use Node app.js. For Mon ...

The Material UI Rating Component is malfunctioning and showing an incorrect value

I'm currently working on a component loop that takes in async data. Everything is rendering properly except for the first component, where the Rating component isn't displaying its value correctly (it just shows 0 stars). Here's the code: & ...

Managing conflicting eslint rules within the AirBNB configuration can be challenging, but here are some best

Hey all, I'm new to Vue and I'm attempting to create a POC. I've set up ESLint with the AirBNB configuration, but I've run into an issue. Here is the section of code where I'm encountering problems within my Axios call: .catch((er ...

Learning to read HTML tags using JavaScript is a valuable skill

I've been struggling with a problem for some time now and I really need help fixing it. Here's the issue: I have an asp:GridView where I store text with HTML tags in my database under an English column. During the DataBound event, I use Context. ...

What is the best way to ensure a multi-page form is validated using HTML5 and JavaScript before progressing to the next page?

Currently, there are two functionalities at play. The submit button is not being recognized while the functionality in JS $(".next").click(function(){..} is working as expected. HTML This section involves 4 fieldsets. I am attempting to validate ...

Using JavaScript, what is the process for getting the value of a child node within Firebase

var ref = firebase.database().ref("games/" + gameId + "/patterns"); ref.on("child_changed", function(snapshot){ var pattern = snapshot.key; console.log(pattern); }); Currently, the code snippet above only logs the key. But how can I extract the player ...

Combining Laravel 5.4 with jQuery for Cross-Origin Resource Sharing (CORS

I have two Laravel applications, one serving as an admin panel and the other as an API server. Attempting to make a jQuery AJAX Post request to the API is resulting in unexpected response behaviors. Using barryvdh/laravel-cors to enable CORS on the API d ...

Cannot access window.top.location in outdated web browsers

I have recently developed a script that redirects users upon page refresh. While it works perfectly on newer versions of Firefox, Chrome, and Internet Explorer, it seems to fail on older browsers which most of my users still use. What steps should I take ...

Deciphering the method to retain added text

Imagine you have this code snippet: $('.button').click(function() { $('body').append("<p>Random Text</p>"); }); Whenever the .button is clicked, text is added to the body. How can we make sure that this text is saved a ...

DevExpress popup remains contained within the iframe and does not overflow beyond its boundaries

My dilemma involves incorporating a FilterControl within an iframe popup. My issue arises when using the column selector (or any other DevExpress combobox), as the popup remains confined within the frame without extending beyond its borders. I am seeking a ...

How can a Vue component be created with a template that solely consists of a property's text?

Looking for a way to incorporate plain text within a Vue component template area? The current method involves wrapping the text in a div, but this causes layout issues when concatenating components with other text fragments. This results in awkward spacing ...

Transform the MongoDB aggregation output by using variable keys

Here is a sample document from the Collection: { "_id" : ObjectId("5fec3b978b34e8b047b7ae14"), "duration" : 20.0, "createdOn" : ISODate("2020-12-16T22:28:44.000Z"), "ClockInTime" : ISODate ...

What is the method for choosing multiple IDs using CSS?

Is there a way to target multiple IDs in CSS? For instance: #test_id_*{ } <div id="test_id_10"></div> <div id="test_id_11"></div> ...

"Utilizing Vue.js to dynamically fill input fields based on the selection of an element

As I am still new to learning Vue.js, I may not be using the correct terminology here. My current project involves a basic Vue application where I have implemented a simple search box functionality. The search box triggers an event (v-on:blur) when text i ...

jQuery validation requires either two fields to be filled out or one other field

I've been searching extensively for a solution that addresses my specific requirements. I have three fields – first name, last name, and business name. My goal is to allow users to input either both their first and last names or just the business na ...

Error: The compilation of the release Kotlin files for expo permissions has failed

I am currently working on creating an apk using the expo bare project. To generate the apk for Android, I have been using the following command: cd android && ./gradlew assembleRelease Unfortunately, every time I run this command, I encounter an ...