What is the process for assigning a background color to a specific option?

Trying to create a dropdown menu with various options and colors. Managed to set background colors for each option, but once an option is selected, the background color disappears.

Is there a way to fix this issue? See my HTML example below:

<select>
  <option style="background-color: green">Successful</option>
  <option style="background-color: orange">Process Failure</option>
  <option style="background-color: purple">Abandoned</option>
</select>

Check it out here as well: http://jsfiddle.net/H8HVm/1/.

Answer №1

If you want to retrieve the class of the selected option using jQuery and set it as the class of the select element, you can use the following code snippet along with a demo:

$("#color_me").change(function(){
    var color = $("option:selected", this).attr("class");
    $("#color_me").attr("class", color);
});
.green {
    background-color: green;
}
.orange {
    background-color: orange;
}
.pink {
    background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="color_me" class="">
    <option class="green">successful</option>
    <option class="orange">process failure</option>
    <option class="pink">abandoned</option>
</select>

You can view the JSFiddle example here: http://jsfiddle.net/DrydenLong/3QUN6/

Explaining the code provided:

$("#color_me").change(function(){ 

This part of the code triggers the function when the element with the id "color_me" is changed, meaning when an option is selected from the dropdown.

    var color = $("option:selected", this).attr("class");

Here, we are capturing the class of the currently selected option and storing it in the variable color. The use of "this" ensures we are targeting the correct select element.

    $("#color_me").attr("class", color);
});

Finally, this line sets the class of the select element to the color class we retrieved earlier.

Answer №2

var x, i, j, selElmnt, a, b, c;
x = document.getElementsByClassName("tt-select");

for (i = 0; i < x.length; i++) {
    selElmnt = x[i].getElementsByTagName("select")[0];
    a = document.createElement("DIV");
    a.setAttribute("class", "select-selected");
    a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
    x[i].appendChild(a);
    b = document.createElement("DIV");
    b.setAttribute("class", "select-items select-hide");
    for (j = 0; j < selElmnt.length; j++) {
        /*for each option in the original select element,
        create a new DIV that will act as an option item:*/
        c = document.createElement("DIV");
        c.innerHTML = selElmnt.options[j].innerHTML;
        c.addEventListener("click", function(e) {
            var y, i, k, s, h;
            s = this.parentNode.parentNode.getElementsByTagName("select")[0];
            h = this.parentNode.previousSibling;
            for (i = 0; i < s.length; i++) {
                if (s.options[i].innerHTML == this.innerHTML) {
                    s.selectedIndex = i;
                    h.innerHTML = this.innerHTML;
                    y = this.parentNode.getElementsByClassName("same-as-selected");
                    for (k = 0; k < y.length; k++) {
                        y[k].removeAttribute("class");
                    }
                    this.setAttribute("class", "same-as-selected");
                    break;
                }
            }
            h.click();
        });
        b.appendChild(c);
    }
    x[i].appendChild(b);
    a.addEventListener("click", function(e) {
        e.stopPropagation();
        closeAllSelect(this);
        this.nextSibling.classList.toggle("select-hide");
        this.classList.toggle("select-arrow-active");
    });
}
function closeAllSelect(elmnt) {
    var x, y, i, arrNo = [];
    x = document.getElementsByClassName("select-items");
    y = document.getElementsByClassName("select-selected");
    for (i = 0; i < y.length; i++) {
        if (elmnt == y[i]) {
            arrNo.push(i)
        } else {
            y[i].classList.remove("select-arrow-active");
        }
    }
    for (i = 0; i < x.length; i++) {
        if (arrNo.indexOf(i)) {
            x[i].classList.add("select-hide");
        }
    }
}
document.addEventListener("click", closeAllSelect);
.tt-select {
    position: relative;
    height: auto;
    padding: 0px;
    margin-bottom: 30px;
    text-align: left;
}
.tt-select select {
    display: none;
}
.select-selected {
    background-color: #fff;
    color: rgba(0, 0, 0, 0.8) !important;
}
.select-selected:after {
    position: absolute;
    content: "";
    top: 14px;
    right: 10px;
    width: 0;
    height: 0;
    border: 6px solid transparent;
}
.select-selected:before {
    position: absolute;
    content: "";
    top: 18px;
    right: 10px;
    width: 0;
    height: 0;
    border: 6px solid transparent;
    border-color: transparent transparent #000000 transparent;
    transform: rotate(180deg);
}
.select-selected.select-arrow-active:before {
    border: none;
}
.select-selected.select-arrow-active:after {
    border-color: transparent transparent #000000 transparent;
    top: 10px;
}
.select-items div,.select-selected {
    color: #ffffff;
    padding: 8px 16px;
    border: 1px solid #333333;
    cursor: pointer;
}
.select-items {
    position: absolute;
    background-color: #313131;
    top: 100%;
    left: 0;
    right: 0;
    z-index: 99;
}
.select-hide {
    display: none;
}
.select-items div:hover, .same-as-selected {
    background-color: rgba(0, 0, 0, 0.1);
}
<div class="tt-select">
    <select>
        <option value="0">Options</option>
        <option value="1">Option One</option>
        <option value="2">Option Two</option>
        <option value="3">Option Three</option>
        <option value="4">Option Four</option>
    </select>
</div>

Check out this CodePen demo.

Answer №3

I've found this code to be effective:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("select").change(function(){
        var color = $("option:selected", this).attr("class");
        $(this).attr("class", color);
    });
});
</script>

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

Different approaches to transforming jQuery code into functional AngularJS code

I am a beginner in AngularJS and I'm looking to implement functionality for a login page similar to the one you see when you click the 'Forgot Password' link: Would it be more appropriate to use a directive instead of a controller for this ...

What could be the reason for my failing express test?

I'm in the process of configuring a server using Node/Express and I want to write ES6 code, so I've incorporated babel into my setup. Currently, the server is operational, and I can successfully make the necessary requests. However, I am facing ...

Transform HTML into PDF while maintaining the original letter spacing

We are in need of converting numerous files to enable search and word highlighting functionality in a web browser, as well as server-side indexing for the searchable words. I have previously utilized an online service like (Step 1, Step 2 on linked page) ...

Understanding how to use the 'this' variable in Vue components is essential for efficiently modifying DOM elements. Let's dive into a clarification on the usage of 'this'

Within my vue component, the structure is as follows: export default{ name: '', data: function () { return { var1 :{}, var2 : {}, ... } }, created: function () { this.methodName1() }, methods: { me ...

Is it possible to transfer data from a JavaScript file to the Express server without relying on a form submission?

As a newcomer here, I apologize if I overlook any best practices. Currently, I am in the process of developing a sudoku game using express, JavaScript, HTML, and mongoDb. My current challenge involves setting up a statistics system. My goal is to send da ...

Display a series of elements in rows using styled-components

Here is a simple array that I need help rendering into a grid structure. Currently, the array is displayed like this: HAMDDN I want each element to be on a new row like so: HA MD DN Any suggestions on how to achieve this? Below is the full code. I am ...

Dynamic divs to occupy the rest of the available vertical area

I have been experimenting with a new website layout and created a form setup. However, I am facing an issue with the fluidity of the layout. While the items are floating into position, there is a problem where if the item on the right is 400px bigger than ...

Acquiring POST parameters within Laravel's Controller from JavaScript or Vue transmission

I am trying to send Form data from a Vue component to a Laravel API using the POST method. Although Laravel is returning a successful response, I am encountering difficulty in handling the POST data within the Laravel controller. Below is the code for th ...

Using ThreeJS to project a texture onto a mesh surface

I am trying to project a texture onto the surface of a mesh using ThreeJS. The link provided achieves the desired result, although I am uncertain about the method used to accomplish it. . As I continue my research, I will update this post. If anyone has ...

The issue I'm facing is that the ng-click functionality in Angular JS is not functioning properly when the

Upon loading the page, my JavaScript function creates a tree structure from JSON data and generates a list of anchor tags which look like this: <a ng-click="shareParent(4619)">Some data</a> Despite associating the ng-click directive with the ...

Obtain the script's event feedback from the WebView and transfer it to React Native

My HTML script is used to display a module, but I encountered an issue with the eventHandler not responding. How can I ensure that the eventHandler in Web View triggers responses? I am not receiving any logs for the onSuccess, onError, or onClose methods w ...

Can the chosen date in a calendar date picker be linked to a variable that is accessible to a separate file?

Currently, I am developing a React application and have integrated a date picker feature using Ant Design to enable users to select a date range. My goal is to store the selected date value into a variable that can be accessed by another file in my progr ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

Displaying videos in full screen using HTML5

I am attempting to create a fullscreen webpage with a video using the following code: <video id="backgroundvideo" autoplay controls> <source src="{% path video, 'reference' %}" type="video/mp4"> </video> ...

In what situations should the `#` symbol be used to select a DOM element?

There are times when I have to retrieve elements in the following ways: var object = document.getElementById('ObjectName'); Other times, it's done like this: var object = document.getElementById('#ObjectName'); What distinguishes ...

Is it possible to request a GET on a server's JSON file using a specific key?

I am currently working on a project involving an auto-suggestion exercise using a JSON file located on a server. I'm not entirely clear on the web development terminology, so one requirement has me a bit confused: The requirement states: "On the keyu ...

Expanding the functionality of Promise to include progress updates

I had the idea to expand Promise by adding a 'progress' feature in order to track progress while using Promise for my asynchronous tasks. So, I created an extended version of Promise like this: class promisePro extends Promise { constructor ...

Angular date control and its corresponding date panel are not properly aligned on the user interface

I am utilizing Angular and Angular Material for date control display. See the code snippet below: <input type="date" (change)="validateDateRange($event,true, index)" class="form-control oot-start-date align-middle" name=& ...

Creating a child div that is half the size of its parent

Is there a way for a child div to inherit half the width and half the height of its parent div without using specific values or viewport units? ...

Looking for a solution to resolve the error in this SQL example?

I'm looking to extract node "-all_models=1-4.htm" in SQL using the example provided. Here is my current code: <div class="models_selector_block" > <DIV class="msb_item"> <a class="ser_active" hr ...