Is there a way to create an HTML select element where each option has a unique background color, and will display properly

I want to create multiple HTML select elements with unique background colors for each option:

<select runat="server" id="select">
<option value="A">White</option>
<option value="B">Red</option>
<option value="C">Yellow</option>
<option value="D">Green</option>

Upon loading the website, I aim to have the select element only show the background color without text for the selected option. The text (white, red, etc.) should only appear when the dropdown is open.

When a user changes the selected value, the background color should also change while keeping the text invisible in the closed dropdown.

I would appreciate it if the solution is compatible with most browsers, including IE 9/10.

Cheers.

Answer №1

Give this code a try - it is compatible with all browsers, including IE:

HTML

<select id="select1" onchange="colourFunction()">
<option class="white" value="A">This should have a WHITE background</option>
<option class="red" value="B">This should have a RED background</option>
<option class="yellow" value="C">This should have a YELLOW background</option>
<option class="green" value="D">This should have a GREEN background</option>
</select>

CSS

#select1 {width:150px; color:rgba(0, 0, 0, 0);}
#select1:focus, #select1:focus {
color:black;
}
.white {background:white;}
.red {background:red;}
.yellow {background:yellow;}
.green {background:green}

JavaScript

function colourFunction() {
var myselect = document.getElementById("select1"),
colour = myselect.options[myselect.selectedIndex].className;
myselect.className = colour;
myselect.blur(); //This just unselects the select list without having to click
somewhere else on the page
}

I hope this helps :)

Answer №2

Check out this jsfiddle link below:

http://jsfiddle.net/xt3xv/1/

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<select runat="server" id="select">
    <option value="A" style="background-color: white;">White</option>
    <option value="B" style="background-color: red;">Red</option>
    <option value="C" style="background-color: yellow;">Yellow</option>
    <option value="D" style="background-color: green;">Green</option>
</select>
<script>
$('#select').change(function(){
      if($(this).val() == 'A'){
        $("body").css('background-color', 'white');
      }
        if($(this).val() == 'B'){
        $("body").css('background-color', 'red');
      }
        if($(this).val() == 'C'){
        $("body").css('background-color', 'yellow');
      }
        if($(this).val() == 'D'){
        $("body").css('background-color', 'green');
      }
    });
</script>
</body>
</html>

Answer №3

   <script>

   function changeBackgroundColor(id,color){

  id.style.backgroundColor=color;


 }
  </script>


    <div id="container">

     <p> Choose a color to update the background:</p>


    <select id="colorMenu" onchange="changeBackgroundColor(container,value)">
   <option value="white"> </option>
   <option value="red">RED</option>
   <option value="blue">BLUE</option>
   <option value="green">GREEN</option>
   </select>


   </div>

Answer №4

This revision closely resembles @Singh's solution with a few adjustments for increased flexibility, allowing for the customization of multiple select elements to change colors.

CSS

<style>
    .red {
        color: darkred;
        background-color: red;
    }

    .purple {
        color: darkmagenta;
        background-color: magenta;
    }

    .yellow {
        color: darkkhaki;
        background-color: yellow;
    }

    .aqua {
        color: mediumaquamarine;
        background-color: aqua;
    }

    .blue {
        color: lightblue;
        background-color: blue;
    }

    .green {
        color: lightgreen;
        background-color: green;
    }
</style>

HTML

<select name="pos1" id="pos1" onchange="colourFunction(this)">
    <option disabled selected value>choose</option>
    <option class="red" value="1">Red</option>
    <option class="purple" value="2">Purple</option>
    <option class="yellow" value="3">Yellow</option>
    <option class="aqua" value="4">Aqua</option>
    <option class="blue" value="5">Blue</option>
    <option class="green" value="6">Green</option>
</select>

<select name="pos2" id="pos2" onchange="colourFunction(this)">
    <option disabled selected value>choose</option>
    <option class="red" value="1">Red</option>
    <option class="purple" value="2">Purple</option>
    <option class="yellow" value="3">Yellow</option>
    <option class="aqua" value="4">Aqua</option>
    <option class="blue" value="5">Blue</option>
    <option class="green" value="6">Green</option>
</select>

JavaScript

<script>
    function colourFunction(pos) {
        pos.className = pos[pos.selectedIndex].className;
        pos.blur();
    }
</script>

Answer №5

<select>
<option  value="AliceBlue">AliceBlue</option>
<option  value="AntiqueWhite">AntiqueWhite</option>
<option  value="Aqua">Aqua</option>
<option  value="Aquamarine">Aquamarine</option>
<option  value="Azure">Azure</option>
<option  value="Beige">Beige</option>
<option  value="Bisque">Bisque</option>
<option  value="Black">Black</option>
<option  value="BlanchedAlmond">BlanchedAlmond</option>
<option  value="Blue">Blue</option>
<option  value="BlueViolet">BlueViolet</option>
<option  value="Brown">Brown</option>
<option  value="BurlyWood">BurlyWood</option>
<option  value="CadetBlue">CadetBlue</option>
<option  value="Chartreuse">Chartreuse</option>
<option  value="Chocolate">Chocolate</option>
<option  value="Color">Color</option>
<option  value="Coral">Coral</option>
<option  value="CornflowerBlue">CornflowerBlue</option>
<option  value="Cornsilk">Cornsilk</option>
<option  value="Crimson">Crimson</option>
<option  value="Cyan">Cyan</option>
<option  value="DarkBlue">DarkBlue</option>
<option  value="DarkCyan">DarkCyan</option>
<option  value="DarkGoldenrod">DarkGoldenrod</option>
<option  value="DarkGray">DarkGray</option>
<option  value="DarkGreen">DarkGreen</option>
<option  value="DarkKhaki">DarkKhaki</option>
<option  value="DarkMagenta">DarkMagenta</option>
<option  value="DarkOliveGreen">DarkOliveGreen</option>
<option  value="DarkOrange">DarkOrange</option>
<option  value="DarkOrchid">DarkOrchid</option>
<option  value="DarkRed">DarkRed</option>
<option  value="DarkSalmon">DarkSalmon</option>
<option  value="DarkSeaGreen">DarkSeaGreen</option>
<option  value="DarkSlateBlue">DarkSlateBlue</option>
<option  value="DarkSlateGray">DarkSlateGray</option>
<option  value="DarkTurquoise">DarkTurquoise</option>
<option  value="DarkViolet">DarkViolet</option>
<option  value="DeepPink">DeepPink</option>
<option  value="DeepSkyBlue">DeepSkyBlue</option>
<option  value="DimGray">DimGray</option>
<option  value="DodgerBlue">DodgerBlue</option>
<option  value="FireBrick">FireBrick</option>
<option  value="FloralWhite">FloralWhite</option>
<option  value="ForestGreen">ForestGreen</option>
<option  value="Fuchsia">Fuchsia</option>
<option  value="Gainsboro">Gainsboro</option>
<option  value="GhostWhite">GhostWhite</option>
<option  value="Gold">Gold</option>
<option  value="Goldenrod">Goldenrod</option>
<option  value="Gray">Gray</option>
<option  value="Green">Green</option>
<option  value="GreenYellow">GreenYellow</option>
<option  value="Honeydew">Honeydew</option>
<option  value="HotPink">HotPink</option>
<option  value="IndianRed">IndianRed</option>
<option  value="Indigo">Indigo</option>
<option  value="Ivory">Ivory</option>
<option  value="Khaki">Khaki</option>
<option  value="Lavender">Lavender</option>
<option  value="LavenderBlush">LavenderBlush</option>

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

A system similar to Facebook's ajax like feature without any errors, yet producing no visible

I am currently in the process of developing a system similar to Facebook's ajax-like feature. Below is the code I have put together: Jquery function for ajax call: function addLikes(likeid, action) { $('.likebox #tutorial-'+likeid+' ...

What is the reason for the undefined output of this verified JSON Web Token (JWT)?

I've been working on decoding a JWT id_token using the libraries jwks-rsa and jsonwebtoken, however, the result keeps coming back as undefined. I understand that this issue is related to callbacks and the need to wait for a response from the getKey f ...

Reveal the inner workings of functions within the Vuex Plugin

I am currently working on setting up a Vuex plugin where I want to make the undo function accessible for use in my component's click events. // plugin.js const timeTravel = store => { // .. other things function undo () { store.commit(&a ...

Having trouble retrieving information from the weather website

Hello, I am interested in extracting weather information from a specific website: On this website, there is a search bar that allows users to enter the name of any city in India. Upon pressing 'Go', the user is directed to a page displaying the ...

How to effectively utilize wrapAsync in MeteorJS when working with callbacks in the vzaar API?

Issue to Resolve: My current challenge involves retrieving an uploaded video ID asynchronously from an API in order to incorporate it into my code once the video upload process is completed. Unfortunately, I am encountering issues where the returned value ...

Maintaining Existing Filters and Incorporating Additional Filters in React/Next.js Data Filtering

I'm currently facing a challenge with filtering data in React/Next.js. The issue I'm encountering is that whenever I set a new filter, the previous filters get removed. For instance, if a user performs a search, it works fine but the tag filters ...

Utilizing JQuery Ajax to Retrieve Conversion Explanations

In my project, I have a set of AJAX wrapper functions that I use to make AJAX requests. I am now considering switching to using the Fetch API instead. As a newcomer to this transition, I have some questions and concerns that I think will be beneficial for ...

python scraping: how to extract two nested elements

Hello, I am looking to extract information from the < del> and < ins> tags below. However, I haven't been able to find a solution yet. Does anyone have any ideas on how to scrape this data? This is my Python code: import requests import j ...

Tips for extracting value from a chosen input field without relying on its unique identifier

I am working on a simple code to help guess notes by ear. The concept involves tabs with empty input fields where numbers need to be entered based on a specific melody for the guitar fretboard. One button reveals the first note, while another button checks ...

When the remove button is pressed, I want the checkbox to become unchecked

I need help with unchecking a checkbox after confirming the removal of items. Can someone provide guidance on how to achieve this? Below is the code I am using: JavaScript: $(".rem-btn").click(function(){ var remConf = confirm("Are you sure you ...

Node.js application for changing attributes in an HTML string

Within my node.js backend, there exists an object with a specific property named content, which stores an HTML string. The content within includes an img tag that currently has a src attribute containing a base64 string. I am seeking to modify this src att ...

Position a dynamic <div> in the center of the screen

My goal is to design a gallery page with a list of thumbnails, where clicking on a thumbnail will open the related image in a popup div showing its full size. The issue I'm facing is how to center the popup div on the screen, especially when each pic ...

constant element within mat-menu in Angular

This coding snippet displays unread notifications to users: <mat-menu #menu="matMenu"> <div class="menu-item" mat-menu-item *ngFor="let item of notifications"> ...item content </div> <b ...

Reorganizing an array of JSON data by date value with a limitation to just one

Currently, I am attempting to organize a JSON array based on the date key. However, it appears that my sorting function is either stopping after one sort or simply not functioning correctly. Here is the JavaScript code for my sorting function: function ...

In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a ...

Disappearing Act: The vanishing act of Bootstrap 4 navbar

Everything works perfectly on a large screen, but disappears when resizing. I haven't specified a height property for the navbar. Here's the Fiddle. I know this question has been asked many times before, but I have yet to find a solution that act ...

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

Resolving Cross-Domain Ajax for Improved API Performance

In the midst of developing an infrastructure to support a gaming platform that will cater to a large user base, performance is our top priority. We are striving to parallelize the architecture by running APIs, databases, and applications on separate server ...

Experiencing a problem with inline JavaScript onclick

I recently came across a fantastic pure javascript code for a smooth scrolling function, but I'm struggling with integrating it into an inline onclick function. My understanding of javascript is quite limited and I could really use some help... <d ...

Discovering the true width of elements that have overflow hidden in IE7 using jQuery

I am dealing with a dynamic list that contains around 50 elements, but the exact number may vary. <div style="width:465px;"> <ul> <li>aaa</li> <li>aaa</li> <li>aaa</li> <li>aaa& ...