HTML code to set the background color of a selection box

Here is an image that relates to my query.

I have created a select box in HTML that contains colors, as shown in the image above and the code below. By using CSS, I have applied classes to color various option elements, but how do I ensure that the selected items are also displayed in their respective colors?

In the image, red is currently selected, yet the background of the selected item remains white. Furthermore, is there a method to remove the hover effect? For instance, when hovering over the orange item, it is highlighted in blue. (Please note that JavaScript and jQuery are used to populate the selector after clicking a button.)

<div class="selection">
    <select id="color">
        <option class="selectionpurple" value="purple">purple</option>
        <option class="selectionblue" value="blue">blue</option>
        <option class="selectionred" value="red">red</option>
        <option class="selectiongreen" value="green">green</option>
        <option class="selectionorange" value="orange">orange</option>
    </select>
</div>

Answer №1

Utilizing the jquery change() function is an effective way to accomplish this task. The change() function is triggered each time an option is selected. By extracting the value of the selected option and utilizing the jquery css() function, you can apply the chosen style to the select element.

var selected = $("select option:selected").val();
$('select').css('backgroundColor', selected);

$( "select" ).change(function () {
    console.log($(this).val());
    $('select').css('backgroundColor', $(this).val())
})
.red {
background-color : red;
}
.blue {
background-color : blue;
}
.green {
background-color : green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="text"> 
  <option value="red" class="red" selected>red</option> 
  <option value="blue" class="blue">blue</option>
  <option value="green" class="green">green</option>
</select>

Answer №2

const chosenColor = $("select option:selected").val();
$('select').css('backgroundColor', chosenColor);

$( "select" ).change(function () {
    console.log($(this).val());
    $('select').css('backgroundColor', $(this).val())
})
.red {
background-color : red;
}
.blue {
background-color : blue;
}
.green {
background-color : green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="text"> 
  <option value="red" class="red" selected>red</option> 
  <option value="blue" class="blue">blue</option>
  <option value="green" class="green">green</option>
</select>

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

Difficulty with JQuery click event not targeting anchor element in Firefox browser

I am facing an issue with my navigation menu targeting anchors positioned by the data-position attribute on a page. The code snippet I am using works perfectly in Safari and Chrome, but sadly it does not work at all in Firefox. Any suggestions on how to ...

Tips for utilizing a protractor ExpectedCondition by hand

Recently diving into Protractor, I'm aiming to set up an expect statement like so: expect(elementIsVisible).toBe(true); While exploring the EC (expected conditions) section in Protractor, specifically EC.visibilityOf, I find myself unsure about the ...

The Datalist HTML does not function properly with line breaks

<input type="text" list="req" name="req" style="width:350px; height:70px;"><datalist id="req"> <option value=""><option> <?php while($getreq = $requirements->fetch_array()){ ?> <option><?=$req = preg_r ...

Issues arise when attempting to make the background image in Bootstrap collapse responsive

Whenever the screen size changes in my code, the collapse icon appears. However, when I click on that icon, none of the contents are visible. Another issue I am facing is that I want the background of the section element to be an image. So, I added a back ...

Getting the values of $scope variables from AngularJS in the controller to the view

I have a simple scope variable on my AngularJS Controller. It is assigned a specific endpoint value like this: $scope.isItAvailable = endpoint.IS_IT_AVAILABLE; How can I properly use it in my view (HTML) to conditionally show or hide an element using ng- ...

Determine whether the parsed JSON item string exceeds a certain number

I am currently working on checking the length of a parsed JSON item to see if it exceeds 17 characters. If it does, I need to display ellipses. The specific item I am focusing on is item.tli. My goal is to create a link with this item. If the length of tl ...

The json_encode function in PHP seems to be unexpectedly adding additional square brackets

When I use json_encode to write code into a JSON file using PHP, it is adding an extra square bracket. Is there a method to create and write a JSON file without this issue? function appendData($data){ $filename='data.json'; // read the file if p ...

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

Tips for maintaining sequential numbering in Mediawiki sections

Looking to enhance the formatting of numbered lists by adding section headers and restarting numbering? The old Mediawiki format supported this, but it no longer works in version 1.24. For example: ==First Header2== # # ==Second Header2== # Desired output ...

Click on the button to convert the content of the text area into a variable

Is there a way to capture all the text inside a textarea or input field as a variable upon button click using jQuery or JavaScript? The .select() function doesn't seem to achieve this, instead displaying numerous CSS properties when logged. What app ...

Ensuring data is saved on multiple forms using ui-router in AngularJS

Implementation Details: I'm currently utilizing ui-router to load a form page in a ui-view div. I found an excellent example by Andres Ekdahi. My question is, how can I perform a $dirty check on multiple forms using the same directive? Form 1 < ...

When the CSS grid is equipped with a sticky left column, it will horizontally scroll if the grid's width exceeds 100% of its containing element

I am facing an issue with a CSS grid layout that has sticky left and right columns as shown below: .grid { display: grid; grid-template-columns: repeat(10, 200px); } .grid > div { border: 1px solid black; background-color: white; } .sticky- ...

Learn how to utilize ng-class to assign an ID selector to HTML elements

In my code, I have an icon that is displayed conditionally using ng-class. I am looking to include ID's for both the HTML elements. <i ng-show="ctrl.data.length > 1" ng-class="{'glyphicon glyphicon-chevron-down': !ctrl.isOpen, ...

Is jQuery returning null because the selected option is not being posted correctly?

I am having an issue with this jQuery script as it is returning null. I have tried different syntax for selected options, but here is the code that I currently have: The script is functioning correctly and successfully runs, enabling me to download the Ex ...

Enhancing xhtml with rich snippets and incorporating microdata for game data

When it comes to rich snippets, are they only for HTML5 or can they also be used in XHTML? My website is built using XHTML. Another question I have is how should I display data with rich snippets for the following: A link to a game that includes name, i ...

The functionality of the Bootstrap toggle button seems to be malfunctioning

I'm having trouble with the toggle button in my Bootstrap code. When I resize the window, the toggle button appears but clicking on it doesn't do anything. This is my first time using Bootstrap, so I might have made some silly mistake. Any assist ...

Determining light sources for unique shapes using Three.js

After creating a custom geometry and successfully using geometry.computeFaceNormals() to achieve correct lighting, I encountered an issue when attempting to animate the geometry. Even though I call geometry.computeFaceNormals() within the animation loop, t ...

How to capture a change event in a dynamically loaded element using JQuery

I am facing an issue with dynamically added rows in my table. Each row contains a select option, and I need to trigger an action when the select is changed. However, since the rows are loaded after the page load, my function does not work as expected. < ...

Hide the Popup once the data has been successfully submitted to the server

I need assistance with closing a popup after saving the information in the database. I attempted to use the code provided below, however, it did not work as expected. <form id="form1" runat="server" > <div> <img alt ...

Arranging JSON array elements in order

Currently in the process of creating an application with jQuery mobile. The data is stored in a JSON file: [{ "title": "title you desire", "url" : "thisistheurl.com" },{ "title": "title you desire", "url" : "thisistheurl.com" },{ "title": "title ...