Adjusting the CSS of the <td> <i> element depending on the value

I have a task to implement validation on values in my table. If the values are greater or less than 0, I need to dynamically change or add/remove the CSS for the corresponding td and i tags.

This is how my table structure looks:

        <table class="table table-hover" id="studentweek">
            <thead>
                <tr>
                    <th>Year</th>
                    <th">Weeks</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>VAR (%)</td>
                    <td class="text-warning"> <i class="classname">-10.65%</i></td>
                </tr>
                <tr>
                    <td>VAR (diff)</td>
                    <td class="text-warning"> <i class="classname">-13,953</i></td>
                </tr>
                <tr>
                    <td>VAR (%)</td>
                    <td class="text-navy"> <i class="classname">8.81%</i></td>
                </tr>
                <tr>
                    <td>VAR (diff)</td>
                    <td class="text-navy"> <i class="classname">11,320</i></td>
                </tr>
            </tbody>
        </table>

Currently, I am manually hard coding the CSS changes, but I would like to automate this based on value changes. Can someone suggest the best way to achieve this?

In my Ajax request, I was thinking of doing something like this:

var sdlyvar = $(parseFloat(".classname").text());

if (sdlyvar < 0){
    $('.classname').removeClass(".classname").addClass("fa-level-down");
} else {
    $('.classname').removeClass(".classname").addClass("fa-level-up");
}

Answer №1

To accurately parse percentages in JavaScript, utilize the parseFloat method by referring to this guide.

var percentageValue = $('#sdlyvar').text();
var parsedPercentage = parseFloat(percentageValue) / 100.0;

if (parsedPercentage < 0){
    $('#sdlyvar').removeClass("fa-level-up");
    $('#sdlyvar').addClass("fa-level-down")
} else {
    $('#sdlyvar').removeClass("fa-level-down");
    $('#sdlyvar').addClass("fa-level-up")
}

Answer №2

The issue you're facing is the inability to compare a string like "-10.95%" with an integer due to the presence of the final % symbol. To resolve this, you need to utilize parseFloat on that value:

var sdlyvar = parseFloat($('#sdlyvar').text());

This function will handle all non-numeric characters following the number.

Additionally, consider removing the opposite class when making updates:

if (sdlyvar < 0){
    $('#sdlyvar').removeClass("fa-level-up").addClass("fa-level-down");
} else {
    $('#sdlyvar').removeClass("fa-level-down").addClass("fa-level-up");
}

Here are a few miscellaneous suggestions:

  1. Clearly state the issues in your code when seeking help on platforms like StackOverflow
  2. When referencing an element multiple times with jQuery, think about storing the selection in a variable, such as var $sdlyvar = $("sdlyvar");: quicker to write and execute.
  3. Minimize unnecessary whitespace when sharing code snippets :/

Answer №3

In this particular code snippet, the function .slice is utilized to remove the % sign from a value. Subsequently, the code compares this modified value and adds or removes classes accordingly.

var sdlyvar = $('#sdlyvar').text();   

if (sdlyvar.slice(0,-1) < 0){
    $('#sdlyvar').removeClass("fa-level-up");
    $('#sdlyvar').addClass("fa-level-down");
} else {
    $('#sdlyvar').removeClass("fa-level-down");
    $('#sdlyvar').addClass("fa-level-up");
}

Answer №4

let items=document.querySelectorAll("tr td i");
for(let item in items){
    if(parseInt(items[item].innerHTML)<0){
        items[item].className+=" fa-level-down";
    } else {
        items[item].className+=" fa-level-up";
    }
}

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

Pass KeyEventArgs object to JavaScript function

Is it possible to pass keydown events as parameters to a JavaScript function in Silverlight4? ...

Displaying a vertical arrangement of collapsed menu items with a centered navbar and logo positioned at the center of it (using bootstrap)

I'm currently working on a website that features a centered navbar with a logo also centered inside it. The tech I'm using is Bootstrap and LESS. Issue When the navbar collapses on mobile/tablet view, the menu items are displayed horizontall ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

The value retrieved from redux appears to be varying within the component body compared to its representation in the return

Trying to fetch the most recent history value from the redux store to pass as a payload is presenting a challenge. When submitting a query, the history updates and displays the latest value within the map() function in return(), but when checking at // CON ...

Tips for verifying if a webpage request originated from a user's inbox

I am currently working on a web application that sends a download link to subscribers. Subscribers can click the link from their inbox to access and download a pdf document. However, I am looking for a way to restrict access to the pdf document only when ...

An issue arises when request.body appears blank within the context of node.js, express, and body

I am currently attempting to send a request to my node server. Below is the xhttp request being made. let parcel = { userId: userId, //string unitid: unitid, //string selections: selections //array }; // Making a Call to the Server using XMLHttpR ...

Obtain the result returned from a JSON using jQuery's Ajax GET

Can you help me figure out how to retrieve the JSON result of a PHP function in an Ajax request for verification purposes in onSucces? public function checkEmailValidityAction() { $is_valid = true; $is_duplicate = false; $email_reset = false ...

Updating the content in an HTML document using jQuery

In my workflow, I am utilizing jquery ajax to retrieve information from a PHP file. data = <option>Peter</option><option>Maria</option> Following that, I aim to leverage jquery to insert this data after the initial option. <s ...

submitting a collection of hashes to a server using jQuery

I'm facing an issue with sending data to the server. I have an array structured like this: places = new Array(); places.push({name: "ci", loc: "bo"}) places.push({name: "ae", loc: "ea"}) if I try to send this data to the server using the following J ...

polygon with five or more sides

Can divs be created with shapes such as five or six corners? I am looking to create clickable zones on a map and any alternative methods would be greatly appreciated. ...

Retrieve a list of Objects from a Spring controller in response to an AJAX request

I am trying to send a List of objects from a Spring controller to an AJAX request. AJAX request: function doAjaxPost(date) { $.ajax({ type : "POST", contentType : "application/json", url : "<%="/water-consumer" + homepageUR ...

Pass data from Angular UI Bootstrap Modal to parent controller upon background click or closing with the ESC key

Hello everyone. Let's dive right into the issue - I am trying to figure out how to pass a variable back from an AngularJS UI Boostrap Modal when the user clicks on the background or presses the ESC button on their keyboard. There are some solutions ...

How can I incorporate Vue draggable feature in my project using cards?

I've been attempting to integrate vuedraggable with Vuetify Cards, but I'm facing an issue where the drag and drop functionality doesn't seem to work when the cards are in a single row. Interestingly, it works perfectly fine when they are di ...

Retrieving JSON data from a URL with PHP

Attempting to retrieve JSON data from the following URL: $search_data&format=json&nojsoncallback=1 The information I am aiming to obtain based on the above link is as follows: { "places": { "place": [ { ...

What would be the best way to display a label once the zoom level exceeds a certain threshold in Leaflet?

As someone new to the Leaflet library and JavaScript in general, I'm currently facing a challenge with showing/hiding a leaflet label based on the zoom level. The markers are within a 'cluster' layer loaded via AJAX callback, and I bind the ...

Creating a responsive YouTube video embed within a div container with a fixed background image

Hello there, I'm currently working on positioning the YouTube Iframe on the background to make it look like the video is playing on a laptop screen. I also want it to scale down appropriately with the background image on different resolutions. The w ...

Creating an opaque effect on a Material UI Drop down menu: Step-by-step guide

For the last half hour, I've been experimenting with my Select dropdown menu in an attempt to make it semi-transparent, but without success. I've tried adjusting the properties of the Paper, then the Menu, and then the MenuList, yet it appears th ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...

What exactly happens behind the scenes when JSON.stringify() is called?

How does the replacer argument function extract keys and values from an object's value and map them to its key and value arguments in the JSON.stringify(value, replacer, space) method? I have grasped that the key of the object becomes the key paramet ...

Can you share any recommendations or instances of modifying data within HTML tables using Laravel?

Has anyone ever needed to directly edit and update data in a HTML table using Laravel? I have successfully created "create" tables for different tasks, but I'm interested in being able to modify the data directly on an "index" page. While there are ...