Adjust the background color of a div based on the value stored in the

Is there a way to dynamically change the background color of a <div> based on database values when different options are selected from a dropdown list? I have been researching extensively and while I found valuable information in previous posts, I am struggling to implement it into my code.

My objective: I need to create a dropdown menu with various temperature options. Each temperature corresponds to a specific color code in the database which should be applied to the <div>.

For example, 99 degrees would result in a yellow background, while 105 degrees would yield an orange background.

Current code: Dropdown menu page

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Alert Test</title>
    <meta/>
  </head>
  <body>
    <p>
    Page copy
    </p>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction_1(){
    var ajaxRequest;

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Oops! We apologize.");
                return false;
            }
        }
    }
    ajaxRequest.onreadystatechange = function (){
        if(ajaxRequest.readyState == 4){
            var ajaxDisplay = document.getElementById('ajaxDiv_4');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }
    var temp = document.getElementById('temp').value;
    var queryString = "?temp=" + temp;
    ajaxRequest.open("GET", "abc.php"+ queryString, true);
    ajaxRequest.send(null); 
}
//-->
            </script>
<form>
<br />
<select id='temp'>
<option value=''>Choose Product</option>
<option value='90'>90</option>
<option value='91'>91</option>
<option value='92'>92</option>
<option value='93'>93</option>
<option value='94'>94</option>
<option value='95'>95</option>
<option value='96'>96</option>
<option value='97'>97</option>
<option value='98'>98</option>
<option value='99'>99</option>
<option value='100'>100</option>
<option value='101'>101</option>
<option value='102'>102</option>
<option value='103'>103</option>
<option value='104'>104</option>
<option value='105'>105</option>
<option value='106'>106</option>
<option value='107'>107</option>
<option value='108'>108</option>
<option value='109'>109</option>
<option value='110'>110</option>
<option value='111'>111</option>
<option value='112'>112</option>
<option value='113'>113</option>
</select>
<input type='button' onclick='ajaxFunction_1()' value='Select' />
        </form>
            <div id='ajaxDiv_4'></div>
            </body>
</html>

Database query code snippet

<?php
include_once('conn.php');
// Retrieve data
if( isset($_GET['temp']) && $_GET['temp'] != '' ){
  $temp = $_GET['temp'];
  $temp = mysql_real_escape_string($temp);
  //query
  $query = "SELECT * FROM temps WHERE temp = '$temp'";
  //Execute
  $qry_result = mysql_query($query) or die(mysql_error());

  while($row = mysql_fetch_array($qry_result)){
    $display_string = '<strong>WARNING</strong> '.$row['alert'].'<br>';
    $display_string .= '<strong>BE AWARE</strong> '.$row['messa'].'<br>';
    $display_string .= '<strong>RESPONSE</strong> '.$row['action'].'<br>';
    $display_string .= '<br>';
  }
  echo $display_string;
} else {
  return null;
}
?>

The dropdown and page functionality is working correctly. The final touch needed is to add some color coding. Any assistance will be greatly appreciated.

Answer №1

My preferred approach for handling such tasks involves a blend of CSS and jQuery. I create CSS classes to represent different temperature ranges:

.temp1{background-color: red}
.temp2{background-color: blue}

Once the temperature data is retrieved, JavaScript and jQuery take over using the addClass() and removeClass() functions along with some conditional logic:

if(temprature > 90) temp = 1;
else if(temprature > 75) temp = 2;
$('ajaxDiv_4').addClass('temp' + temp);

Alternatively, you could replace the while loop with this snippet:

if($temp > 100) $class = temp1;
else if($temp > 80) $class = temp2;
else $class = temp3;
while($row = mysql_fetch_array($qry_result)){
$display_string = '<strong class=' . $class . '>WARNING</strong> ' . $row['alert'] . '<br/>';
$display_string .= '<strong class=' . $class . '>BE AWARE</strong> ' . $row['messa'] . '<br/>';
$display_string .= '<strong class=' . $class . '>RESPONSE</strong> ' . $row['action'] . '<br/>';
$display_string .= '<br/>';
}

Answer №2

Why not render the dropdown option elements with pre-defined colors instead of making an AJAX call every time a user makes a selection? For example:

<option value='104' data-color='yellow'>104</option>

This way, you can easily retrieve the color value in your click handler without additional requests.

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 dynamic table displaying data fetched from a MySQL database, with the added functionality of seamlessly filtering the table content without the need to refresh the

Currently, I am developing a website that showcases leaderboard data retrieved from a MySQL database in the form of a table. The users have the ability to filter and search through this data. By utilizing PHP calls, I was successful in constructing the tab ...

Exploring the Use of State Objects in React

In my search for understanding how to properly set state in React components, I came across this helpful question. Although it clarified setting state correctly, I still struggle with the proper way to test state based on a variable. Let's consider a ...

Having trouble fetching JSON on the server (NodeJs) as I keep receiving the error "Unexpected Token U in position 0"

I have gone through several posts on dealing with sending and retrieving JSON using NodeJs and Express, but I am still struggling to make it work. Someone mentioned that the issue might be due to invalid JSON. var arr = { City: 'someplace', Coun ...

The custom validation in Node.js using Express-Validator is ineffective

I have implemented custom validators using express-validator to include specific validations: middlewares.js module.exports = function (app) { console.log('making sure I am being called'); return function (request, response, next) { ...

What is the reason for JavaScript documentation using a nested array to define a function's parameters in its syntax?

I'm struggling to articulate my question, but as I delve into the documentation for JavaScript and Node.js, I notice they define syntax in a way such as this. var new_array = old_array.concat(value1[, value2[, ...[, valueN]]]) It seems like all th ...

What is the process for logging data to a file in AngularJS?

I have a question regarding writing logs in an AngularJS project. Which logging method should I use to write logs to a file? Should I use Angular's $log or log4javascript? I currently have the following code configuration for using Angular's $log ...

The GitHub Fetch polyfill fails to submit form body when used with a React form component

Using the fetch API polyfill from GitHub in conjunction with React, I encountered a challenge while trying to submit a form. The example provided for form submission is shown below: var form = document.querySelector('form') fetch('/users&a ...

Combine entities in Firebase when the names match

Currently, I am developing a simple shopping cart application. Whenever a user clicks on the Add To Cart button, I save the product in the database as an array item. If a user tries to add multiple items of the same product, I aim to group all products, ...

Calculating the combined total and mean values within an object using JavaScript

I have a set of data in the following format: { "Dates": ["January", "January", "March", "March", "March", "November", "November"], "Values": [45.6, 0.5, 59.3, 46.56, ...

Enhancing text visibility in dompdf by making it bold or increasing its size

Recently, I began using dompdf v0.6.0beta3 along with the dompdf Codeigniter helper in Codeigniter. To address the issue of missing fonts, I manually moved the Arial font family tff files from the Windows 7 font folder to the /lib/fonts directory within do ...

Utilize flexbox to align two buttons side by side and manage their positioning

I have a collection of buttons that I want to display in rows of two. I am looking for a way to set the specific width of each button and decide whether they should be aligned left, center, or right. Ideally, the outcome would resemble the following: http ...

Setting up the default path that appears in the URL

Looking to simplify the URL path on your website? When developing webpages, you may have addresses like: www.example.com/index.html www.example.com/about_us.html www.example.com/en/index.html Is there a way to make these URLs more concise, such as: www ...

Tips for assigning information from a react hook within a function or event

Currently, I am in the process of learning how to create hooks in order to efficiently reuse data that needs to be modified across different components. For my project, I am utilizing Material UI's Tabs and require the use of a custom hook called use ...

Issue in Babel: The preset 'latest' could not be located in the directory even though it was installed globally

I executed a global installation of Babel using: npm install -g babel-cli npm install -g babel-preset-latest Although it is generally not recommended to install Babel globally, I find it preferable in order to maintain a clean directory structure without ...

Issue with the dimensions and proportions of the canvas

After creating a canvas with HTML and setting the ratio to 16/9 in the CSS, I specified a width of 100vw and added a border. However, I noticed that the canvas appeared larger than expected on the screen. #canvas{ width: 100vw; aspect-ratio: 16/9; border: ...

Creating full-width divs using BootstrapLearn how to easily create full-width div

Bootstrap is being utilized in my current project. I have been creating divs inside columns, but they are not extending to the full width of the columns. Below is a snippet of the code: <!DOCTYPE html> <html lang="en"> <head> ...

Utilizing intricate CSS selectors for integration testing with webdriverjs

In my quest to develop integration tests using Selenium with JavaScript bindings, WebdriverJS, Mocha, and Chai, I stumbled across an interesting suggestion in this article. It proposed using WebdriverJS over the official SeleniumJS bindings for some reason ...

Execute a function when scrolling occurs, without the page itself scrolling

On my webpage, I have a div positioned on top of the page's content that I want to lift up like a curtain upon the first scroll event without actually scrolling the page itself. Once the curtain div has been raised, I would like the scrolling to retu ...

An effective method for converting MongoDB's JSON array of UTC dates to local time using Node.js

Using Node.js to query MongoDB and encountering an issue with Date (ISODate) fields. After querying, the Date format returned is as follows: DT : 2014-10-02T02:36:23.354Z The goal is to efficiently convert the DT field from UTC to Local Time ISOString. F ...

Changing the Style Sheets on the Fly

I have designed a grid of 5x5 boxes. My goal is to be able to click on a link and have that specific link change color after it has been clicked (a:visited) - one at a time. Unfortunately, my current code changes the color of all the links instead of just ...