Changing the background color based on the selected value in the dropdown menu: a step-by-step guide

I am looking to update the header color based on the selected option in a drop-down menu. For example, if option 1 is chosen, the data-background-color will switch to green.

HTML:

<div class="card-header" data-background-color="blue" style="position: relative; padding:25px;">
  <h4 class="title" style="font-family: 'Josefin Sans', sans-serif;">
    <b>Heading</b>
  </h4>
</div>
<div class="col-md-3 col-sm-3 col-xs-6">
  <div class="form-group">
    <div class="input-group">
      <span class="input-group-addon">
      <i class="material-icons">account_balance</i>
      </span>
      <select type="text" class="form-control validate" id="optionSelect">
        <option value="-1">Select Shift</option>
        <option style="border-left-color:#2ecc71;" value=1>DAY</option>
        <option style="border-left-color:#3498db;" value=2>NIGHT</option>
        <option style="border-left-color:#f1c40f;" value=3>AFTERNOON</option>
      </select>
    </div>
  </div>
</div>

Jquery

$('#optionselect').on('change', function() {

            var shift = $('#optionselect').val();
            if (shift === 'DAY') {
                $('#ftagHeader').css({
                    'background-color': 'green !important'
                });
            }

        });

The data-background-color attribute will be adjusted based on the selection made in the drop-down menu. Please share any insights on how this can be achieved. Thank you!

Answer №1

You can implement the onchange event using jQuery with the following code snippet.

var colors = {
  1: "blue",
  2: "brown",
  3: "red"
}


$("#optionSelect").on("change", function(event) {

  console.log("Selected value: ", event.target.value);
  $(".card-header:eq(0)").attr("data-background-color", colors[event.target.value]);
  $(".card-header:eq(0)").css("background-color", colors[event.target.value]);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card-header" data-background-color="blue" style="position: relative; padding:25px;">
  <h4 class="title" style="font-family: 'Josefin Sans', sans-serif;">
    <b>Title</b></h4>
</div>

<div class="col-md-3 col-sm-3 col-xs-6">
  <div class="form-group">
    <div class="input-group">
      <span class="input-group-addon">
        <i class="material-icons">account_balance</i>
      </span>
      <select type="text" class="form-control validate" id="optionSelect">
         <option value="-1">Choose Option</option>
         <option style="border-left-color:#2ecc71;" value=1>Option 1</option>
         <option style="border-left-color:#3498db;" value=2>Option 2</option>
         <option style="border-left-color:#f1c40f;" value=3>Option 3</option>
       </select>
    </div>
  </div>
</div>

Answer №2

const selectElement = document.querySelector('#optionSelect');
const headerDiv = document.querySelector('.card-header');
selectElement.addEventListener('change', handleSelectChange);

function handleSelectChange(event) {
  event = event || window.event;
  const selectedElement = event.target || event.srcElement;
  const selectedValue = selectedElement.value;
  let backgroundColor = headerDiv.getAttribute('data-background-color');
  
  if (selectedValue === '1') {
    backgroundColor = 'green';
  }
   
  headerDiv.setAttribute('data-background-color', backgroundColor);
  console.log(headerDiv.getAttribute('data-background-color'));
}
<div class="card-header" data-background-color="blue" style="position: relative; padding:25px;">
<h4 class="title" style="font-family: 'Josefin Sans', sans-serif;">
<b>Heading</b></h4>
</div>


<div class="col-md-3 col-sm-3 col-xs-6">
    <div class="form-group">
       <div class="input-group">
<span class="input-group-addon">
 <i class="material-icons">account_balance</i>
</span>
<select type="text" class="form-control validate" id="optionSelect">
   <option value="-1">Select Shift</option>
    <option style="border-left-color:#2ecc71;" value="1">DAY</option>
  <option style="border-left-color:#3498db;" value="2">NIGHT</option>
    <option style="border-left-color:#f1c40f;" value="3">AFTERNOON</option>
</select>
</div>
</div>
</div>

Answer №3

$('#optionSelect').on('change', function() {
          switch ($(this).val()) {
            case '1':
              $('.card-header').attr('data-background-color', 'day');
              break;
            case '2':
              $('.card-header').attr('data-background-color', 'night');
              break;
            case '3':
              $('.card-header').attr('data-background-color', 'afternoon');
              break;
          }
        });
        
[data-background-color='blue'] {
          background-color: blue;
          color: #FFF;
        }

        [data-background-color='day'] {
          background-color: yellow;
          color: #000;
        }

        [data-background-color='night'] {
          background-color: #000;
          color: #FFF;
        }

        [data-background-color='afternoon'] {
          background-color: orange;
          color: #FFF;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

        <div class="card-header" data-background-color="blue" style="position: relative; padding:25px;">
          <h4 class="title" style="font-family: 'Josefin Sans', sans-serif;">
            <b>Heading</b></h4>
        </div>

        <div class="col-md-3 col-sm-3 col-xs-6">
          <div class="form-group">
            <div class="input-group">
              <span class="input-group-addon">
                <i class="material-icons">account_balance</i>
              </span>
              <select type="text" class="form-control validate" id="optionSelect">
                <option value="-1">Select Shift</option>
                <option style="border-left-color:#2ecc71;" value=1>DAY</option>
                <option style="border-left-color:#3498db;" value=2>NIGHT</option>
                <option style="border-left-color:#f1c40f;" value=3>AFTERNOON</option>
              </select>
            </div>
          </div>
        </div>

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

Hovering does not activate the CSS dropdown

I have been struggling to implement a pure CSS menu that shows on hover. Although everything seems to work fine, I encounter an issue when trying to hide and then show the menu again upon hover. Here is the HTML code: <ul id="nav-menu"> <li& ...

The UglifyJsPlugin in Webpack encounters an issue when processing Node modules that contain the "let" keyword

Below is the code snippet from my project which utilizes Vue.js' Webpack official template: .babelrc: "presets": [ "babel-preset-es2015", "babel-preset-stage-2", ] webpack.prod.config.js new webpack.optimize.UglifyJsPlugin({ compress: { ...

Download our jQuery Fileupload control complete with a progress bar for free today!

Do you know of any free jQuery file uploader plugins with a progress bar? I need one for my classic-asp website. ...

Change the background color of a div element dynamically

Is there a way to dynamically apply a background color to only the first 5 div blocks in React? Here is my code snippet: const ImageBlock = ({block}) => { const number = 5 return ( <React.Fragment> {block.map((item, index) => ...

Ways to display additional information in typeahead using Angular JS

Currently, I am using the Bootstrap directory typeahead in Angular. I am looking to display more results in my HTML template instead of just the name: typeahead="job as job.name for job in getJobPlace($viewValue) | filter:{name:$viewValue}" I would like ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Tips for preventing redundant data fetching when the page loads with react-query

I am working on a React.js page where I need to fetch data from an API using react-query. I want to store the API data in cache for the first visit, and then always retrieve it from the cache afterward. How can I prevent the API request from being refetch ...

Troubleshooting issue with the transition of carousel images in ui.bootstrap.carousel

I am currently facing an issue with the angular-ui bootstrap carousel (referenced at http://angular-ui.github.io/bootstrap/). The problem I am encountering is that the transition effect is not functioning as expected. Instead of smoothly moving from right ...

Error encountered when executing axios in Redux action

Hey there, I'm utilizing redux to handle API calls in order to render the json response on my web application. I've been attempting to log the responses to troubleshoot the issues but it doesn't seem to be working as expected? dashaction.js ...

Angular4 and jQuery working together for effective navigation and pagination

Trying to implement pagination in angular 4 and jQuery, but encountering an issue where clicking on the next button causes it to skip through multiple pages at once (2, then 3, then 5)... Component code: addClass(x) { $(".page-item").click(function () ...

Obtain the data stored in an object within an array

I am attempting to retrieve the values of objects within an array. const bugSchema = new Schema({ title: { type: String, required: true }, comments:[ { user:{ type: String, required: true }, c ...

How can I ensure the footer stays at the bottom of the page using a table layout?

For quite some time now, I've been working on achieving a table layout with a sticky footer. My specific requirement is for the footer to remain fixed at the bottom even when zooming in or out. However, whenever I try to adjust the zoom level of the w ...

"Event triggered upon completion of jqgrid data retrieval from dataurl

Utilizing jQuery to fetch a list of suppliers based on a part number, I aim to load additional data concerning the supplier/part number combination once the edit form is displayed. The issue arises from the fact that the dataurl method, which is invoked in ...

Error: Unable to locate module - google-spreadsheet due to missing dependency 'child_process'

I've been working on saving form data to a spreadsheet in Next.js, but I keep encountering an error as soon as I try to import the google-spreadsheet module. An Error Has Occurred: https://i.sstatic.net/iQWPa.png ./node_modules/google-spreadsheet/ ...

What is the process for loading my new fonts into an HTML document?

I am trying to incorporate two specific fonts, bigsmalls-bold and lft-etica-web, into my CSS and HTML code. Unfortunately, I have been unable to find a way to download these fonts directly. The only information I found was a JavaScript code snippet on I a ...

Seeking a regular expression to identify special characters appearing at the beginning of a string

I'm looking to update my current regex pattern to include special characters at the beginning of a string value. Here's what I have right now: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+.]{ ...

HTML 5 - GRUNT BUILD: The error message "Fatal error: Object has no method 'compact'" is causing issues with the build process

Currently, I am working on a project using GRUNT. However, I encountered an error while building the project: Running "cuff:dev" (cuff) task >> Building src/pages/home Fatal error: Object home.less has no method 'compact' The erro ...

Learn how to fetch user-selected options in Node.js and display the corresponding file contents in a textarea after submission

Hello, I am new to Node.js so please be patient with me. I am struggling to figure out how to retrieve the selected option from a drop-down list after a user submits it and then perform an action based on that choice. Here is an example of what I have in m ...

Include a photo in the notification when utilizing the sendToTopic function

I am looking to utilize the sendToTopic method for sending notifications to a topic. Is there a way to include an image in the notification? It seems that notification.imageUrl is not available as an option. ...

Positioning of bottom navigation bars

Is there a way to ensure that the bottom navigation bar remains fixed at the bottom of the screen, regardless of the device's screen size? position: absolute; bottom: 0; width: 100%; While this solution works, it has been observed that when th ...