Choose a unique text color

Having trouble with my HTML select form and modifying text color for specific options. In the provided example, I changed the color for the Tuesday option, but it only shows up when scrolling through the options. How can I make the color change visible for Tuesday even when it's selected at the top?

Fiddle:https://jsfiddle.net/bb61c412/280/

Code:

.form-control {
  color: blue;
}

.selected {
  color: red;
}
<link rel="stylesheet" type="text/css" href="https://bootswatch.com/bower_components/bootstrap/dist/css/bootstrap.min.css" />

<form action="#" id="form" method="post" data-toggle="validator" style='text-align:center;'>
  <div class="form-inline">

    <select class="form-control" name="date">
      <option value="0">
        Date
      </option>
      <option value="1">
        Monday
      </option>
      <option value="2" selected class="selected">
        Tuesday
      </option>
      <option value="3">
        Wednesday
      </option>
      <option value="4">
        Thursday
      </option>

    </select>

  </div>

</form>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

Answer №1

Check out the updated Jsfiddle!

Change color of selected text option

jQuery:

$(function(){
    $("select").on("change", function(){
    $("select option").css("color", "blue");
    $(this).find("option:selected").css("color", "red");
  })
})

$("select option").css("color", "blue");

This line resets the color to blue for all options.

$(this).find("option:selected").css("color", "red");

This line changes the color to red for the selected option in the select box.

Answer №2

Here is a clever method that maintains each option's unique color while setting the selected option at the top to the same color.

Update

Interestingly, Firefox and Edge/IE struggle to retrieve the actual style of an option element. To work around this issue, a "dirty trick" was devised. A data-color attribute is added to both the select and option elements. If an option has a data-color attribute, it will use that color; otherwise, it will default to the color specified in the select's data-color attribute.

function updateColor(el) {
  var color = el.options[el.selectedIndex].getAttribute('data-color');
  if (color) {
    el.style.color = color;
  } else {
    el.style.color = el.getAttribute('data-color');
  }
}
// Set color on page load
updateColor(document.querySelector('.form-control'))
.form-control,
.form-control option {
  color: blue;
}
.form-control option[data-color='#090'] {
  color: #090;
}
.form-control option[data-color='#f00'] {
  color: #f00;
}
.form-control option[data-color='#00f'] {
  color: #00f;
}
.form-control option[data-color='#0ff'] {
  color: #0ff;
}
<form action="#" id="form" method="post" data-toggle="validator" style='text-align:center;'>
  <div class="form-inline">
    <select data-color="#00f" class="form-control" name="date" onchange="updateColor(this);">
      <option data-color="#090" value="0">
        Date
      </option>
      <option data-color="#090" value="1">
        Monday
      </option>
      <option data-color="#f00" value="2" selected class="selected">
        Tuesday
      </option>
      <option data-color="#0ff" value="3">
        Wednesday
      </option>
      <option data-color="#0ff" value="4">
        Thursday
      </option>
    </select>    
  </div>
</form>

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

Error encountered while using JQuery Ajax to invoke server-side method in ASP C#

How can I call a server-side method using AJAX in an ASP C# application? I have the below code in my aspx file: function editApp(appID) { $.ajax({ type: "POST", url: "Default.aspx/GetSquare", contentTy ...

Adjust the IFrame scrollbar position to the top

How can I position the scrollbar at the top of an IFrame used for horizontal scrolling through a gallery? Is there a trick in CSS or jQuery to achieve this, considering I am using a .Net backend? Any suggestions on controls or alternative methods to solve ...

A guide on dynamically adjusting image size in ReactJS

Here is the structure I have: img { width: auto; height: 200px; } .cards { display: flex; justify-content: center; margin-top: 2em; width: 80%; flex-wrap: wrap; } .card { margin: 1em; box-shadow: 0 0 6px #000; ...

I desire my grid to exhibit an identical appearance to that of the jquery datepicker

I have an interactive element called the "open grid" that, when clicked on, reveals a grid of buttons. I'm looking for help with coding it so that instead of being displayed below the textbox, the grid of buttons can be hovered over the "open grid" li ...

Issue: Inability to scroll on div overflow section

My website consists of one static page with an HTML and CSS file. Oddly enough, when testing the page and inputting content into a multiline textarea until it overflows, the browser fails to display a scrollbar. Despite inspecting the div with the id &apos ...

Modify dates on constant URL and run the link

I've got a link that looks like this: Is it possible to create an HTML form with two input date fields and merge them into a single link similar to the one above? I want to select dateFrom and dateTo separately, then click GO to access the link. I&a ...

Contrasting v-on:click and onclick in Vue.js

Can you explain the distinction between v-on:click="..." and using onclick="..." in Vue.js? I am aware that with v-on:click, the handler must be written inside the Vue object (as shown in the documentation example), but what are the be ...

What is the purpose of having the same function for onPress in React Native components?

As a beginner in learning react-native, I like to search random projects on GitHub and analyze what seems weird or hard to understand. Today, I came across some code from an unknown individual that looked like this: {isTrue && ( <Touch ...

Exploring the world of lighting and shadows in WebGL and Three.js

I'm having difficulty focusing lights on specific targets, specifically the main character, while also darkening the background. Additionally, I'm experiencing issues with the shadows not working properly in my code snippet related to lights and ...

What is the best method to modify the hover text color in a Bootstrap navbar?

Whenever the cursor hovers over the letters, I attempted to modify their color, but unfortunately, it didn't work as expected. nav a { text-decoration: none; } .logo { height: 3rem; } .navbar-nav .nav-item .nav-link.custom:hover { color: ...

Focusing on the combination of Phonegap, Angular JS, and Onsen for app development

We are working on developing an app using PhoneGap, Angular JS, and Onsen. One issue we are facing is that we are unable to center the header in a modal. The code snippet is provided below: <ons-modal var="modalVariable"> <ons-navigator var"de ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...

How to give focus to a div in IE 8 after pressing the tab key, no jQuery required

We are facing a challenge with our datagrid where we have implemented navigation using the tab key. In IE 7 & 8, pressing the tab key shifts the focus away from the grid to the next element on the page. While in other browsers, we were able to prevent thi ...

Displaying and concealing table rows based on selected items

After spending a whole day trying to get this HTML/java script to work properly, I came across some code online that I used here. My goal is to have the "Colors*" row not displayed when the page loads, but to show the color options when a shirt size is sel ...

Retrieving journal web addresses using the CORE API

I am currently working on pulling journal data from the CORE API in React, specifically focusing on obtaining the title and URL of each journal. My goal is to create clickable links that direct users to the specified URLs. { "identifiers": [ ...

Using the Jquery .each loop is a powerful way to

I'm just getting started with jquery and I'm working on a .each loop that uses AJAX to fetch data and update list elements. Currently, the .each loop processes all list elements simultaneously... but what I really need is for it to process them o ...

Structured chat interface with unchanging top and bottom sections

I'm currently trying to come up with a way to structure my chatbox so that it has a fixed header at the top and a fixed footer at the bottom, while allowing the chatbox body to scroll within those constraints. I've experimented with various appro ...

Executing a javascript file inside a jade document

I need help incorporating a JavaScript file into my Jade file so that it runs every time the page is accessed. How can I achieve this? Here is my current code snippet: doctype html html head title= title body h2 Bus Driver Locati ...

unable to successfully execute jQuery popup close functionality

I have a button on my mobile site that I want to function as follows: Upon clicking the button, a popup should appear with text and an OK button. When the OK button is clicked, the popup should disappear without affecting the page. My code for this functi ...

Prevent your HTML tables from overflowing

I am attempting to create an HTML table with three columns, where I want the first and third columns to have a width of "auto" based on their content. The middle column should then take up the remaining space. While this setup works well when the content ...