Modify the CSS class of a <TD> element depending on the value of the column using JavaScript

I am working on a grid where I need to dynamically change the CSS of one of the columns based on the value from another field in the result set.

Instead of simply assigning a class like

<td class='class1'>
    ${firstname}
</td>

I am thinking along the lines of

{{if anotherColumnIsTrue }}
 <td class='class1'>
  ${firstname}
 </td>
{{/if}}
{{if !anotherColumnIsTrue }}
 <td class='class2'>
  ${firstname}
 </td>
{{/if}}

Do you think this idea is feasible?

Answer №1

I find that using jQuery simplifies this process.

This can definitely be achieved. Let's say you need this for each row in a table like the one below:

<table id="coolTable">
    <tr>
        <td class="anotherColumn">True</td>
        <td class="firstName">Chris</td>
    </tr>
    <tr>
        <td class="anotherColumn">False</td>
        <td class="firstName">Roger</td>
    </tr>
</table>

You can loop through each row and add classes selectively with code like this:

$(function(){
    $("#coolTable tr").each(function(i,row){
        if($(row).children("td.anotherColumn").html()=="True") // Add your condition here
        {
            $(row).children("td.firstName").addClass("class1");
        } else {
            $(row).children("td.firstName").addClass("class2");
        }
    });
});

Check out this demo on JSFiddle: http://jsfiddle.net/mrfunnel/LXq3w/2/

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

By simply clicking a button, you can input a value into a field without the need for the page to refresh

Can someone please help me figure out how to insert a specific value into an input field without refreshing the page? I have tried the following code but it doesn't seem to work. Basically, when I click the button, I want the value "1234567" to be aut ...

Transform an array of string values that occur multiple times into an array of objects organized by their index

Assuming I have a list structured as follows: [ "id1", "01-01-2019", "name1", "€ 5,60", "id2", "02-01-2019", "name2", "€ 5,70", "id3", "03-01-2019", "name3", "€ 5,20", ... ] and my goal is to transform it into a list of JSON objects ...

Steering your pop up to the top with CSS

Seeking advice on how to position my pop-up at the top of the page and resize it to better fit the screen. Here is where you can find my landing page: yogavoga.com/2weekdiet Grateful for any assistance provided. .modal-content { margin: 5px auto; bac ...

Ways to transfer data between Angular controller and jQuery

Looking for some guidance on how to toggle between two HTML divs based on user input validation using an Angular controller and jQuery animations. Each div contains input fields that need to be validated before moving on to the next stage. Here is a simpli ...

Skipping $state.go in AngularJS UI-Router

My AngularJs application is designed to navigate to the login page if the user is not logged in and attempts to access a route that requires authentication. if ($localStorage.globals.access_token) { $rootScope.globals = $localStorage.globals; $sta ...

What is the best way to create an arrow connecting a parent div to multiple child divs?

I'm faced with a challenge involving a reusable React list component that supports nested children. My goal is to visually connect the parent div to its direct children using arrows, similar to the image linked below. View List Component Image Below ...

Unable to display content on page when using node.js and express

I have organized my controllers in the following manner... const Landmark = require('../models/landmark'); function indexRoute(req, res, next) { Landmark .find() .exec() .then((landmark) => res.render('/landmarks/index', { l ...

Guide on including a callback function in the renderCell columns of Material UI X Datagrid

When a button is clicked and the redux action is successful, I am trying to use a simple toast hook to display a message in the parent component where my Data grid is located. Can a callback be passed to utilize this hook from within the data grid? Here i ...

Triggering a JQuery Toggle Button

This is the code I'm currently working with: $('.access a').toggle(function() { $('link').attr('href', 'styles/accessstyles.css'); $('body').css('font-size', '16px'); }, fu ...

JavaScript: utilizing JSON, implementing dynamic methods for creatures, and utilizing closures for encaps

Apologies for the unclear title, but I am unsure where the issue lies. Therefore, my task is to create a function that generates JavaScript objects from JSON and for fields that start with an underscore, it should create setters and getters. Here is an e ...

Completion of the form within the Bootstrap popover

I have a feature where dynamically created rows contain an "add" button. When the user clicks on the add button, a form is loaded into a Bootstrap popover. See FIDDLE DEMO My issue is: Why isn't this code being triggered? I am trying to validate ...

If element Div is labeled as either A, B, or C, it should smoothly fade out and then fade in as Div

I'm currently working on enhancing the navigation of my portfolio website and I’m facing a challenge in adding additional properties to my toggle() function. This basically involves creating a filter system with four possible options, which are: ...

When experimenting with React JS, I attempted to trigger a modal to open upon clicking a card but unfortunately, the modal did not appear as expected

I'm currently facing an issue where I want to open a modal when clicking on a card. My setup involves using a button with a card component nested underneath it. import React from 'react'; import ReactDOM from 'react-dom'; import & ...

Exploring a property within a JavaScript object

Within my code, I am working with an array of objects called user. When I try to log the first object using console.log(user[0]);, I receive this output: Object {activityId: "2", id: "1", activityDt: "01/15/2016"} Afterwards, I attempt to store user[0] in ...

Leveraging the spread operator for setting state in a series of consecutive updates

Within my component, I am retrieving values from local storage and attempting to load them into the state when the component mounts. However, only the last property that I add seems to be included in the state. I have confirmed that all values are present ...

"Efficiently storing huge amounts of data in MySQL in just 5

Interested in my tech stack: express + typeorm + mysql Seeking a solution for the following task: I have a csv file with over 100000 rows, where each row contains data such as: reviewer, review, email, rating, employee, employee_position, employee_unique_ ...

What is the best way to distribute multiple inline-block elements evenly?

Is it feasible to evenly distribute numerous elements in a div with adjustable width? Check out this example that doesn't work. While using text-align:center; will center the elements, margin:0 auto; does not have any effect. I am aiming for somethin ...

Make a POST request using AJAX to the current page and retrieve a value using the $_POST method

I've been trying to solve this puzzle, but I can't seem to figure out what's going wrong... Here's the situation: I'm passing a value to a function and using AJAX to send this value via a POST request to the same page. Upon succes ...

Next.js server-side rendering encountered an issue with hydration

I'm currently facing issues while using the react-i18next dependency with next.js. Within my _app.js file, I have the following code snippet: if (!isServer) { init_i18n(); } function MyApp({ Component, pageProps }) { // The presence of this ...

interactive form fields updating using javascript

Hey there! I'm a beginner in web development and currently facing a challenge. I have a form with 2 fields generated by one drop-down menu. I've managed to generate one field, but struggling to get the other due to my limited knowledge. I just ne ...