Customizing the background color of an option using HTML and CSS

I am currently developing an option form where each selection will appear in a different color as the user scrolls down. Once a selection is made, it should be saved and displayed with the chosen color.

https://i.sstatic.net/gvdpt.png

My goal is to save the form, return to the page later, and see my previously selected options along with their associated colors (similar to what is shown in 2021). How can I ensure that the selected option box retains the color of the choice from the drop-down list? What steps should I take to ensure that the selection persists when revisiting the page?

HTML

<form action="" method="post">
{% csrf_token %}
        {% for year in years %}
        <select name="rating" id="{{year.id}}">
        <script src="{% static 'SCS/scripts/script.js' %}"/></script> 
            <option>Choose From List</option>
            <option class=green value="green">High</option>
            <option class=yellow value="yellow">Medium</option>
            <option class=orange value="orange">Low</option>
            <option class=gray value="gray">N/A</option>
        </select> 
            <input type="hidden" name="year" value={{year.fy_year}}>
        {% endfor %}
        <input id=save_cap type="submit" value="Save">
      </form>

CSS

.green{
    background-color: green;
}

.yellow{
    background-color: yellow;
}

.orange{
    background-color: orangered;
}

.gray{
    background-color: gray;
}

Answer №1

If you want to achieve your objectives, utilizing JavaScript is essential.

In order to ensure that the selected box option corresponds to the color of the dropdown option, you can use the following code:

document.getElementById("rating").addEventListener("change", function() {
    this.className = this.value;
});

This snippet captures the chosen option value and applies it as a class name to the select element. To make it functional, remember to assign values to each option:

<select name="rating" id="rating">
    <option class=white value="white">Choose From List</option>
    <option class=green value="green">High</option>
    <option class=yellow value="yellow">Medium</option>
    <option class=orange value="orange">Low</option>
    <option class=gray value="gray">N/A</option>
</select>

To store the selected option, you will need to utilize localStorage:

let selected = localStorage.getItem("selected");
let rating = document.getElementById("rating");

if (selected) {
    rating.selectedIndex = selected;
    rating.className = rating.value;
}

rating.addEventListener("change", function() {
    localStorage.setItem("selected", this.selectedIndex);
    this.className = this.value;
});

View the working JSFiddle here.

Answer №2

My expertise lies in jQuery, so delving into this has been quite enlightening for me. Nonetheless, I've managed to come up with a solution for you. Let's walk through my thought process, and below is the code snippet (it seems to only work locally and on the w3 demo due to cookies):

  1. Begin by adding values to the options:

    <option class="green" value="high">High</option>
    for easy retrieval and storage of values in a cookie by clicking here

  2. Attach a change event listener to change colors, with s as follows:

    s.addEventListener('change', changeColor);

  3. Change the color using

    this.className += this.selectedOptions[0].className;
    . More details can be found here

  4. Save the information in a cookie with setCookie(this.id, this.value);. Further insights available here

  5. With color changes and stored cookies in place, we must load any stored values upon document ready. Here's how:

    let cookie = getCookie(`select-${s.id}`);
            // if cookie is not empty, set selected option and change color
            if (cookie != '') {
                s.value = cookie;
                s.className += s.selectedOptions[0].className;
            }
    

Now we have:

  • Dynamic color changing
  • Saved values
  • Loaded values

The other answer may introduce a more efficient, compact method of achieving this. Nevertheless, I trust that the provided links will enhance your understanding of the concept :)

// Setting up onChange event listeners
function setSelectOnChangeListeners() {
  // Retrieve all <select> elements
  const selects = document.getElementsByTagName("select");

  // For each <select> element
  for (s of selects) {
    // Add an onChange event listener to trigger function changeColor();
    s.addEventListener('change', changeColor);
  }
}

// Change color upon <select> onChange event based on selected option color class
function changeColor() {
  console.log(`class = ${this.selectedOptions[0].className}`);

  this.className = '';
  this.className += this.selectedOptions[0].className;

  setCookie(this.id, this.value);
}

// Format cookies as "select-<id> = <val>"
function setCookie(id, val) {
  document.cookie = `select-${id}=${val}`;
  console.log(`Cookie data set for ${id}, ${val}`);
}

// W3 method for getting cookies
function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

// On document load
document.addEventListener('DOMContentLoaded', function(event) {
  // Load cookie data for each select element
  const selects = document.getElementsByTagName("select");
  for (s of selects) {
    let id = s.id;
    let cookie = getCookie(`select-${s.id}`);

    if (cookie != '') {
      s.value = cookie;
      s.className += s.selectedOptions[0].className;
    }
  }

  // Set event listeners
  setSelectOnChangeListeners();
});
.green {
  background-color: green
}

.yellow {
  background-color: #ff0
}

.orange {
  background-color: #ff4500
}

.gray {
  background-color: gray
}
<select id="2020" name="rating">
   <option>Choose From List</option>
   <option class="green" value="high">High</option>
   <option class="yellow" value="medium">Medium</option>
   <option class="orange" value="low">Low</option>
   <option class="gray" value="none">N/A</option>
</select>

<select id="2021" name="rating">
   <option>Choose From List</option>
   <option class="green" value="high">High</option>
   <option class="yellow" value="medium">Medium</option>
   <option class="orange" value="low">Low</option>
   <option class="gray" value="none">N/A</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

Exploring the capabilities of querying HTML using XPath with Python's lxml library

After reading an HTML page as a string, I am using tree = html.fromstring(data). Now, I aim to utilize lxml xpath for querying. Here is an example of the specific part that piques my interest: <table class="class"> <tbody> <tr> &l ...

IE9 crashes when displaying elements with float:left style

After clicking the "off" and then "on" hyperlink in the provided HTML snippet, IE9 crashes. Here is the simplified version of the code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML> <HEAD& ...

How can I create a JSON output from my MySQL database that includes the total count of records per day for a Task entry?

I am looking to implement the JavaScript library called Cal-Heatmap (https://kamisama.github.io/cal-heatmap/) to create an Event style heatmap similar to GitHub's. The objective is to visualize the number of actions taken on each Task record in my Pr ...

Using es6 map to deconstruct an array inside an object and returning it

I am looking to optimize my code by returning a deconstructed array that only contains individual elements instead of nested arrays. const data = [ { title: 'amsterdam', components: [ { id: 1, name: 'yanick&a ...

Why is it that this particular line of code sometimes gives me an "undefined" result before returning an actual value?

Why does the method 'equal' always return with an "undefined" followed by a number? And when I try to parse it, it returns me a NaN. <!DOCTYPE> <html> <head> <script> var fnum = 0; var secondNum; var operation; functi ...

While attempting to upload a file in my Mocha Node.js test, I encountered the message: "Received [Object null prototype] { file: { ... }}"

Everywhere I find the solution in white : app.use(bodyParser.urlencoded({extended: true})); I can use JSON.stringify(req.files) However, I am sure there is a way to fix my problem. My Mocha test : it('handles file upload', async function () { ...

What is the methodology behind incorporating enumerations in typescript?

I've been curious about how typescript compiles an enumeration into JavaScript code. To explore this, I decided to create the following example: enum Numbers { ONE, TWO, THREE } Upon compilation, it transformed into this: "use strict ...

How to incorporate sound files in JavaScript

I have a collection of small audio files that I want to play sequentially, not all at once. To do this, I am using the Audio object in JavaScript as shown below: var audio_1 = new Audio(); var audio_2 = new Audio(); var audio_3 = new Audio(); audio_1.src ...

Managing empty props in React applications

I am facing an issue where I need to display an image fetched from an API on app start, but when I try to render it in React, the application crashes with the error message: TypeError: Cannot read property 'icon' of undefined. Although the icon ...

Displaying TestNG Reporter information in Gradle-generated HTML test reports

I've been searching high and low for a solution to my problem with no luck, so I'm turning directly to you. Is there any way to display TestNG's Reporter output in Gradle HTML reports? Here's the scenario: I have multiple testNG test m ...

Can a webpage be redirected to another page while passing along the id from the original page?

https://i.sstatic.net/3LhYJ.png I have a page that displays shop names and addresses along with an edit function in views.py: def update_shop(request, id): context = {} # * fetch the object related to passed id obj_shop = get_object_or_404(VideoL ...

What is the best way to align a div right below an image that has been clicked on?

I am designing a website that features social media icons spread out horizontally across the page. When a user clicks on one of these icons, I envision a pop-up window appearing below it, displaying additional information. Here is a visual representation o ...

Optimal method for creating a seamless loop of animated elements passing through the viewport

My challenge involves managing a dynamic set of elements arranged next to each other in a row. I envision them moving in an infinite loop across the screen, transitioning seamlessly from one side to the other, as illustrated here: https://i.stack.imgur.com ...

How can I ensure that my content stays fixed at the bottom of a scrolling div in Material UI React?

I have developed a React JS component using Material UI that includes a chat input feature. However, I am facing an issue where the width of the chat input is always half the screen size on desktop or mobile devices. When I try to change the width to 100%, ...

The method for retrieving values and $id from a $firebaseArray using angularJS

Hey there, I'm fairly new to working with Firebase and I seem to be stuck on a problem that I can't find a solution for despite looking in many different places. Here is the structure of my Firebase database: I am trying to retrieve data from a s ...

Click on the radio button to delete all selected entries in the option dropdown

After spending the entire day trying to find a solution, I am still struggling with a simple task - how do I clear all selections from a group of select option drop downs at once without removing them? I want the selections to revert back to their default ...

Having issues with Sencha Touch not initiating in mobile browsers

For quite some time now, I have been developing a mobile app using Sencha Touch 2.1 and conducting tests primarily on desktop Chrome and an iOS PhoneGap / Cordova package. Recently, I made the decision to release it as a "native" app while also offering re ...

The Javascript slider fails to function properly when utilizing AJAX to load the page

I have encountered an issue while trying to open an HTML page using ajax when a button is clicked. The HTML page that I am opening contains a JavaScript slider that functions properly when opened individually, but stops working if opened through my index. ...

Content escapes its parent container and seamlessly transitions to the following element

I am facing an issue with the layout of my element, which includes an image and text centered inside a parent container. Whenever I try adding more elements below the existing image and text, the green text with a red border overflows the current parent . ...

Simulating an ES6 module that returns a factory function for moment.js

Disclaimer: I'm a beginner with Jest so please bear with me. I'm currently working on testing a Vue2.js filter named DateFilter using Jest. This filter simply formats a date that is passed to it. DateFilter.js import Vue from 'vue'; ...