Is there a way to dynamically alter the text color in a tag based on its value?

Utilizing ajax technology, I aim to dynamically populate a div tag with values from a table. I believe that implementing a loop is crucial in this scenario, but the challenge lies in executing it correctly.

My current setup involves xampp for backend php development.

index.php

<li class="nav-item">
    <a href="#" class="btn btn-info" role="button" 
    onclick="taskphp()">Tasks</a>
</li>

javascript.js

function taskphp() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("body").innerHTML = this.responseText;
            let states = document.getElementsByClassName("state");
            Array.from(states).forEach((state) => {
                switch(state.innerHTML) {
                    case "fixed":
                        state.style.color = "green";
                        break;
                    case "fixing in progress":
                        state.style.color = "yellow";
                        break;
                    case "not fixed":
                        state.style.color = "red";
                        break;
                    default:
                        state.style.color = "white";
                }
            });
        }
    };
    xhttp.open("GET", "IT/tasks.php", true);
    xhttp.send();
}

tasks.php

<?php while($row = $result->fetch_assoc()) {
    echo "<tbody><tr>";
    echo "<td>".$row["task"]."</td>";
    echo "<td>".$row["description"]."</td>";
    echo "<td>".$row["task_objects"]."</td>";
    echo "<td class=\"state\">".$row["state"]."</td>";
    echo "<td>".$row["entrance_date"]."</td>";
    echo "<td>".$row["execute_date"]."</td>";
    echo "<td>".$row["source"]."</td>";
    echo "<td>".$row["month"]."</td>";
    echo "</tr></tbody>";
}
?>

With the help of a switch statement, I managed to alter the color of only the initial element in the collection. However, my goal is to dynamically adjust the colors of all elements based on their respective values.

Answer №1

Here are a few key considerations to take into account:

By assigning the id "state" to multiple elements, you are violating the rule that an id should be unique within an HTML document. Instead, consider using classes which can be shared among multiple elements. Modify your PHP code as follows:

echo "<td class=\"state\">".$row["state"]."</td>";

This way, all elements with the class 'state' can be selected as an array using getElementsByClassName. You can then iterate through this array and apply a switch statement to each 'state' element individually:

const states = document.getElementsByClassName("state");
for (const state of states) {
    const stateValue = state.innerHTML;
    switch(stateValue) {
        case "duzelib":
            state.style.color = "green";
            break;
        case "duzelme prosesinde":
            state.style.color = "yellow";
            break;
        case "duzelmeyib":
            state.style.color = "red";
            break;
        default:
            state.style.color = "white";
    }
}

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

Inserting jQuery into a Div container

I am attempting to execute a jQuery function within a dynamically generated div (subpage) through JavaScript. I'm relatively new to this, so please bear with me. Within the index.html file, I am filling a div using a JavaScript load command. <ul& ...

Making a switch from one image to another - JavaScript

I need a solution to swap out an image that is used in multiple locations on a webpage. Consider this sample HTML page: <html> <head> </head> <body> <img id="1" src="example.com/img/1889.png"> <d ...

Twitter typeahead not functioning properly when used in conjunction with ajax requests

I have limited experience in the frontend world and I'm currently working on getting this to function properly. $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 6 }, { source: function (query, ...

Display images from the wikipedia API using asynchronous JavaScript and XML (AJAX

I am attempting to display the images from a Wikipedia article. For example, from To work around the cross-origin policy, I am using a proxy: function imageWp() { var word = 'Appendizitis'; $.ajaxPrefilter( function (options) { if (options ...

The Chrome browser is failing to detect the hover function of the Surface Pen stylus

Encountering an issue with the hover pseudo-class not functioning properly on Surface pad's Chrome browser. The hover effect is working as expected in other browsers, but not in Chrome. I am using a Surface pen to test the hover functionality. HTML: ...

Transfer all HTML variables using AJAX with jQuery

Is it possible to pass all HTML tag values to another file using AJAX? $.ajax({ url:"myp.php", type:'POST', data: //here I want to include all possible element values in the current HTML document }); Any suggestions or ideas on how to ...

Strong tags within MFC

Is it possible to create labels in MFC (Static text) that contain both bold and non-bold text? For instance, something like this: "I want my label to have a mix of styles like this" Any suggestions on how to achieve this? I am aware that I can change ...

Tips for creating a more seamless box transition within HTML

I've been searching for information on this topic, but I haven't been able to find a satisfactory answer. I want to create a div that displays "Contact Us" and when clicked, smoothly reveals a layer with input fields. I know I can use JavaScri ...

The silent button malfunctioning - Ionic

Within the html file: <video preload="metadata" muted="true" controls playsinline webkit-playsinline loop> Despite the "muted" tag, the video is playing with sound in both the browser and on the device. After referencing the video and setting the ...

The Angular Factory service is accurately retrieving data, but unfortunately, it is not being displayed on the user interface

Here is a link to the complete source code angular .module('app') .factory('Friends', ['$http',function($http){ return { get: function(){ return $http.get('api/friends.json') .t ...

Declare webpage as manager for mailto links

One interesting feature I've observed in various web-based email providers is the ability to add the website as the default mailto links handler in browsers like Firefox and Chrome. This means that when clicking on a mailto: link, it will automaticall ...

CSS deep level selectors

For the following HTML/CSS code, I am trying to target only level 1 "row" elements and not their nested counterparts. However, when using the child selector, it still selects the nested elements. How can I achieve selecting only level 1 "row" elements? ...

What is the process for inputting client-side data using a web service in ASP.NET?

Currently experimenting with this: This is my JavaScript code snippet: function insertVisitor() { var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>' $.ajax({ type: "POST", url: pageUrl + "/inse ...

PHP failed to receive Angular post request

My form consists of just two fields: <form name="save" ng-submit="sap.saved(save.$valid)" novalidate> <div class="form-group" > <input type="text" name="name" id="name" ng-model="sap.name" /> </div> ...

Steps to sending an email to an administrator using PHP and jQuery

I am looking for a way to send a notification email to my site admin whenever a user submits a request via a form. Currently, I have the following code that is supposed to link to a PHP file on my server to handle the email sending: $("#modelform").submit ...

Displaying the servlet response within an iframe

This is the content of Content.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> &l ...

Learning how to utilize getDerivedStateFromProps over componentWillReceiveProps in React

To address a deprecated error, I am looking to update my code from using componentWillReceiveProps to getDerivedStateFromProps. The component is being passed a date prop, and whenever this date changes, the getList function needs to be run with the new dat ...

Positioning text at the bottom of a label

My goal is to align the text at the bottom of labels with a fixed height of 3em. This means that labels with one line of text should have the text aligned at the bottom, while labels with two lines should have the second line appear at the bottom. In my l ...

Tips for creating a 360 x 235 degree FOV image using three.js

My camera captures round images with a 235-degree field of view, like this one: https://i.sstatic.net/qNfrX.jpg I am familiar with threejs and have successfully rendered 360x360 images as equirectangular projections. However, I want to use threejs to rend ...

jQuery address plugin does not function properly when content is being replaced

I have been utilizing the jQuery address plugin to allow for back-button functionality, and it has been working well. However, I am running into an issue when the link is within the AJAX content area. For instance: <div id="content"> <a href="e ...