Adjust the color of an HTML table cell based on the selected value in a drop-down menu?

<!DOCTYPE html>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.MRG{ background-color:#82E0AA; }
.MRA{ background-color:#F5B041; }
.MRR{ background-color:#EC7063; }
</style>
</header>
<body>
<table class="table table-hover table-condensed" border="1px">
  <thead>
    <tr>
  <td>Made Ready</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
  <select>
<option class="MRR">Red</option>
<option class="MRA">Amber</option>
<option class="MRG">Green</option>
  </select>
  </td>
    </tr>
  </tbody>
</table>
</body>
</html>

When I have a situation where an HTML table contains a drop-down list in one of its cells, I might want the cell's background color to change based on the selected value from the drop-down list.

The drop-down list consists of three options: Red, Amber, and Green.

To implement this functionality, I am exploring possibilities using JavaScript or CSS to dynamically change the table cell's background color according to the selected option.

For instance, selecting Green from the drop-down list should result in the HTML table cell changing its background color to green.

If you have any insights or suggestions on how to achieve this effect using JavaScript or CSS, I would greatly appreciate it!

Answer №1

Does this meet your requirements?

document.querySelector('select').onchange=updateColorIndicator;

var indicator = document.getElementById("color-indicator");

function updateColorIndicator(event) {
    indicator.classList = this.value;
}
.MRG{ background-color:#82E0AA; }
.MRA{ background-color:#F5B041; }
.MRR{ background-color:#EC7063; }
<table class="table table-hover table-condensed" border="1px">
  <thead>
    <tr>
      <td>Status</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="color-indicator">
        <select>
          <option value="MRR">Red</option>
          <option value="MRA">Amber</option>
          <option value="MRG">Green</option>
        </select>
      </td>
    </tr>
  </tbody>
</table>

Answer №2

  <html>
  <header>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  </header>
  <body>
  <table  id="myTable" class="table table-hover table-condensed" border="1px">
    <thead>
      <tr>
      <td>Completion Status</td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
      <select id="mySelect" onchange="changeColor()">
      <option value="red" class="MRR">Red</option>
      <option value="yellow"   class="MRA">Yellow</option>
      <option  value="green"  class="MRG">Green</option>
      </select>
      </td>
      </tr>
    </tbody>
  </table>
  <script>
    function changeColor(){
        document.getElementById("myTable").style.backgroundColor = document.getElementById("mySelect").value
    }
  </script>
  </body>
  </html>

Demo https://jsfiddle.net/95wvnh0x/7/

Answer №3

To properly identify and manipulate your elements, make sure to give them unique IDs. Then you can implement a solution similar to the following:

<select id="dropdownMenu">...</select>
<td id="tableCell">...</td>
<script>
    document.getElementById('dropdownMenu').addEventListener('change', function (event) {
        document.getElementById('tableCell').className = event.target.value;
    });
</script>

Answer №4

Using just three simple lines of code:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<!DOCTYPE html>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.MRG{ background-color:#82E0AA; }
.MRA{ background-color:#F5B041; }
.MRR{ background-color:#EC7063; }
</style>
</header>
<body>
<table class="table table-hover table-condensed" border="1px">
<thead>
<tr>
<td>Made Ready</td>
</tr>
</thead>
<tbody>
<!-- Add class name for tr -->
<tr class="changeColor">
<td>
<!-- Add id for select -->
<select id="colorChanger">
<option class="MRR">Red</option>
<option class="MRA">Amber</option>
<option class="MRG">Green</option>
</select>
</td>
</tr>
</tbody>
</table>

<!-- Add this script -->
<script>
$('#colorChanger').on('change', function() {
$('.changeColor').addClass($('#colorChanger :selected').attr('class'));
});
</script>

</body>
</html>

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

Creating a unique JavaScript script that gradually adjusts the background color using the setTimeout() function

Is there a way to create a function that continuously changes the background color every 15 seconds by picking colors from an array that starts over once all colors have been used, without having the function run just one time? $(document).ready(() => ...

Having trouble with CSS3 radio buttons not functioning properly on Firefox?

Does anyone know why my CSS3 pseudo elements are working fine in Chrome, but reverting back to default styling in Firefox for my radio button? Any suggestions? Check out this JSFIDDLE link for reference: JSFIDDLE Here is the HTML code snippet: <input ...

"How can I adjust the height of a Bootstrap column to match the height of its neighboring column

In my Bootstrap 4 layout, I have set up two columns... The left column contains three cards in columns The right column has a list group The content in the list group is longer than that of the cards on the left side. Is there a way to make the height ...

"Enhancing user experience in ASP.NET by updating an updatepanel manually to provide feedback during the

My website includes a code-behind file and a separate class with a function that takes a significant amount of time to complete. I want to display information to the visitor when this function sends back a string. To achieve this, I utilize a delegate to ...

Encountering the "Invalid JSON primitive" issue when making an AJAX request in MVC

Despite my efforts to resolve the "Invalid JSON primitive" issue by reading various references, I have not been able to find a solution. As a last resort, I am sharing my code in its simplest form and still encountering the error. See below for the minimal ...

Exploring and accessing information with ajax and php

I'm in a bit of a coding dilemma and could really use some prompt assistance to complete my project. I've managed to retrieve all the data from the database, but when I try to click on the view button, the details don't appear in the modal f ...

Tips for resolving image path issues in slider functionality

My banner sliding function isn't working and the image paths are also not being recognized var img = document.getElementById('img-banner'); var images = [ '../banners/banner.png', '../banners/banner1.png', ...

The response body from the HTTP request is consistently empty or undefined

While working with two containers managed by Docker Compose, I encountered an issue where the response body from a GET call made by a Node.js service in one container to an API in another container using the request module was consistently empty or undefin ...

Fill the image with width using Mat

While working on creating cards using Angular Materials, I encountered an issue where the image was not filling up the space as desired. The red area in the image indicates where I want the image to take up space. https://i.sstatic.net/vcc9U.png HTML: & ...

Steps to prevent the browser's back button from functioning

Similar Question: Disabling Back button on the browser Is there a way to prevent users from using the back button in their browser by using JavaScript? ...

Creating intricate filters using React's map functionality

QUESTION HAS BEEN UPDATED. I am currently working on implementing a filter for my map, allowing users to specify which options they want to view using multiple selection boxes. However, I am encountering an issue with the page that appears after the user ...

Responsive CSS images with overlays

I need to stack two images on top of each other while ensuring they remain responsive with a percentage width and height. <div class="container"> <img src="res/bigger.png/> <img src="res/smaller.png class="icon"/> </div> ...

Utilizing JavaScript to Parse Datasnap Output

I am currently working on a project in Delphi where I need to display a list of data in a listbox. However, I am struggling to understand how everything comes together. Luckily, I found a helpful answer that provided me with a solution using a dataset def ...

Saving HTML form data to a text file

I have a form on my website's index.html that looks like this: <form id="demo" action='submit.php' method='post' enctype='text/plain'> link: <input type='text' name='web'></br> <i ...

transferring data between pages with ajax

I need to retrieve data from another page and display it on my current page using ajax. I have the following code snippet: <script> $(document).ready(function() { $(".link").on("click", function(e) { e.prevent ...

The Stylebook in Delphi 10 Seattle does not apply correctly on forms other than the Main form

Within my application's MainForm, I have 3 Stylebooks available for users to choose from. Once a selection is made, the same Stylebook is applied to other Forms within the program. While most of the styles are properly set, there is one toolbar that s ...

"Encountering an issue with logging in the Node.js application on Heroku. Error

As a beginner on Heroku, I am facing an application error when trying to run my node.js app for the first time. I am having difficulty identifying the issue as the program works perfectly locally. Below is the log. If necessary, I can provide the node.js c ...

Initialize an array containing five zero elements

How can I initialize an array with 5 zero elements in JavaScript without using the classic var arr = [0, 0, 0, 0, 0] method? I've tried a few variations: var arr = new Array(5).map(() => 0); var arr = new Array(5).map(function () {return 0;}); va ...

What is the best way to eliminate an iframe from inside itself using javascript?

Although I am aware of similar questions being asked before, I find myself having to raise this question again along with some attached code because I am struggling to figure it out. In my JSF project, I have two .xhtml files. The first one is mainPage.xht ...

Is there a way to display the destination of a hyperlink as the link text without duplicating it in the HTML/CSS source code?

Is there a way to automatically generate link text from the hyperlink destination without manually typing it out in the source code? I am using a Markdown file with basic HTML and CSS to list external links to academic papers. For instance, can a link be d ...