Displaying JSON data with dynamic color changes in an HTML table: A comprehensive guide

Scenario: I am currently working on a project where I need to fetch data from an external json file, parse it, and then dynamically add it to an HTML table using the footable jQuery plugin.

Question: I have a query regarding how to use JavaScript to parse this json data and based on the value of a specific name/value pair, display the text in a different color within the table. Currently, everything is being displayed in plain text.

The object COPD_QUAL.MED_ASSESS is crucial here as I want to style its display based on its value. For instance,

If COPD_QUAL.MED_ASSESS is "Mild exacerbation" - Display in green, bold text.
If COPD_QUAL.MED_ASSESS is "Moderate exacerbation" - Display in yellow, bold text.
If COPD_QUAL.MED_ASSESS is "Severe exacerbation" - Display in red, bold text.

I already have the code to append the data to the table. Can someone guide me on how to add conditional statements to achieve the above styling? Should I include these conditions within my createPatientTable function?

if (window.location.hostname == 'localhost') {
    console.log('local');
  $.ajax({
      type : 'GET',
      url  : 'json/gtw_copd_mpage3.json',
  dataType : 'json',
   success : function(json) {

        createPatientTable(json);
            },
            error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(thrownError);
  }
        });
}else{
    var getPatients = new XMLCclRequest();
    getPatients.onreadystatechange = function () {
        if (getPatients.readyState == 4 && getPatients.status == 200) {
            var json = $.parseJSON(getPatients.responseText);
            createPatientTable(json);
    };
}
};

});

function createPatientTable(json) {
$.each(json.LIST, function(i, COPD_QUAL) {
    $('.footable > tbody:last').append('<tr><td>' + COPD_QUAL.PATIENT + '</td><td>' + COPD_QUAL.FIN +'</td><td>' + COPD_QUAL.NURSE_UNIT + '</td><td>' + COPD_QUAL.ROOM + '</td><td>' + COPD_QUAL.BED +'</td><td>' + COPD_QUAL.ATTENDING_PHYS + '</td><td>' + COPD_QUAL.LENGTH_OF_STAY + '</td><td>' + COPD_QUAL.MED_ASSESS + '</td></tr>');
});
$('.footable').footable();
};

Here is a snippet of the json array present in the file:

{"COPD_QUAL":"15","LIST":[   {"PATIENT":"TEST, TRICKLE","FIN":"70100905","NURSE_UNIT":"TIC","ROOM":"C219","BED":"A","ATTENDING_PHYS":"LEVITEN , DANIEL L","LENGTH_OF_STAY":"161days 20:15:24","MED_ASSESS":"Mild exacerbation"}...

Answer №1

Here's a suggestion for your code snippet:

/* ... */
+ '</td><td>' + COPD_QUAL.LENGTH_OF_STAY +
'</td><td class="assessment ' + getSeverity(COPD_QUAL.MED_ASSESS) + '">' +
COPD_QUAL.MED_ASSESS + '</td></tr>')

Utilize the following function to determine severity levels:

getSeverity = (function() {
    var lookup = {
        "Mild exacerbation": "mild",
        "Moderate exacerbation": "moderate",
        "Severe exacerbation": "severe" // avoid duplicate entries
    };
    var defaultValue = "unknown"
    return function(assessment) {
        return lookup[assessment] || defaultValue;
    };
}());

To style, use the CSS below:

.assessment {font-weight: bold;}
.mild {color: green;}
.moderate {color: yellow;}
.severe {color: red;}

Answer №2

Why not simply include an if statement that assigns a specific class to the corresponding row:

var classification = '';
if(COPD_QUAL.MED_ASSESS == "Mild exacerbation"){
    classification = 'mild';
} else if (COPD_QUAL.MED_ASSESS == "Moderate exacerbation") {
    classification = 'moderate';
} else if (COPD_QUAL.MED_ASSESS == "??? exacerbation") {
    classification = 'severe';
}

Afterwards, update your tr tag to:

"<tr class="' + classification + '">...

Remember to define the styles for .mild, .moderate, and .severe in a CSS stylesheet.

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

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

Performing multiple http requests in a loop and combining the retrieved data using AngularJS

I am currently working with a piece of source code that looks like this: var projectPromises = $http.get('http://myapi.com/api/v3/projects?private_token=abcde123456'); $q.all([projectPromises]).then(function(data) { console.log(data); ...

Using Jquery Datatables to populate with an asp.net webmethod through ajax calls

When it comes to using ajax with a webmethod to populate something or a table, I usually don't have any issues. However, I've been struggling to find a way to incorporate the jQuery datatables plug-in into my workflow. $.ajax({ type: "POST", ...

Launch a bootstrap modal from a different webpage

If you're looking to open multiple modals with different content displayed from HTML files, check out this example below: <div id="how-rtm-works" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" ...

Unable to automate the selection of a dropdown menu using Selenium WebDriver

I am currently utilizing http://www.makemytrip.com/ This is the HTML code. <div class="mrgnBot30 clearFix"> <span class="watch_icn flL"></span> <div class="widget_inner clearFix suggest_me padBot15 flL"> <h3 class="clearFix has ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...

Ways to prevent users from manually inputting dates in date fields

I am currently developing an application and I need to prevent users from manually entering a date in the type=date field on the HTML page. I want to restrict users to only be able to select a date from the calendar display, which is in the format MM/DD/YY ...

Creating an associative array in javascript: A step-by-step guide

I require an array to be structured in the following manner: {"3": {"label":"All i want for christmas", "song":"Alliw_1405399165.mp3", "name":"All i want for christmas"}, "4": {"label":"Call your girlfriend robyn clip", "song":"Gang ...

Leveraging Angular's catchError method to handle errors and return

One of my challenges involves a model class that represents the server response: class ServerResponse { code: number; response: string; } Whenever I make api calls, I want the response to always be of type Observable<ServerResponse>, even in ...

Deselect the DOM element

Here is a jQuery code snippet: $(document).ready(function () { $(".story-area > h1, .story-area > p, .story-area > div > p").text(function () { return convertString($(this).text()); }); }); Additionally, there is a function de ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...

Hover function not functioning properly

I can't figure out why this hover effect isn't working, there doesn't seem to be a negative z-index or anything like that. At most, it just flashes on hover; .menu{ border-radius: 50%; width: 100px; height: 100px; background: white; box-sha ...

CSS alone has the power to make multiple elements react to a hover action on a div

Is there a way to dynamically change the size of multiple div elements on hover? In this example, we can see how one div element's size changes when hovering over another div element: https://jsfiddle.net/9510a6kj/ .left, .right{ float:left; ...

Utilizing vertical stacked labels in Chart JS for a unique presentation style

Issue with horizontal labels in ChartJS. How can array objects be correctly passed to labels in ChartJS? When passing an array from PHP to ChartJS to create horizontal labels for the chart, they are stacking on top of each other instead of displaying prope ...

Navigating through JSON data retrieved from a MySQL database or within Xcode

In my app, customers are prompted to specify the features they are looking for in a rental car. These preferences are then sent to my Database where a search is performed to determine the number of available cars that match the criteria. I am currently co ...

Encountering an "AJAX not a function" error while using the d3/flask interface

Hey there! I'm new to the world of JavaScript and AJAX. Take a look at this d3 function I've been working on: var node = g.selectAll(".node") .data(root.descendants()) .enter().append("g") .attr("class", function(d) { return "node" + ...

Only the main page is accessible quickly through Express

Currently, I am delving into learning Express and leveraging FS to load my HTML Page. My research on this topic only led me to references of using ASP.NET instead of Express. Here is a snippet from my Server.js file: var express = require('express&a ...

Store the sum of Jquery variables in MySQL database

I have a jquery function that calculates the sum of values from input checkboxes, and I'm looking to store this sum in a PHP variable. However, I am unsure of how to achieve this. Can anyone provide guidance? I am new to jquery and struggling with thi ...