Change the color of the text based on its value

Within my .ejs file, I am passing an array called todolist containing objects of type todo. These objects have keys named: Action / Date / Priority

I want to display the values of these keys, with the priority text appearing in red if the priority is >3, orange if the priority is ==3, and green if the priority is <=2. The code snippet below shows how this is implemented.

Snippet from my code:


    <ul id="list1">
     <% todolist.forEach(function(todo, index) { %>
         <li><a href="/todo/delete/<%= index %>">✘</a> 
             <%= todo.action %> <%=todo.date%> (Priority: <div id="prio<%index%>"><%=todo.priority%>/5)</div>
         </li>
     <% }); %>
    </ul>

    <script>
        $('#list1 div').each(function() {
            if ($(this).text() <= 2) $(this).css('color', 'green');
            else if ($(this).text() == 3 ) $(this).css('color', 'orange');
            else $(this).css('color', 'red');
            console.log("I'm in");
        });
    </script>

I suspect that my function may be conflicting with an external CSS stylesheet. Additionally, I am not seeing the "I'm in" message in my console, and I'm unsure why this is happening. Any assistance would be greatly appreciated. Thank you!

Answer №1

Your code has a syntax error that needs to be corrected. The line else (this).css should actually be else $(this).css. Additionally, your if/else conditional structure is incorrect. It currently reads as if/if/else, but it should be if/elseif/else. Here is the corrected version of your code:

$('#list1 div').each(function() {
  var priority = $(this).text().substr(0,1);
  if (priority <= 2) $(this).css('color', 'green');
  else if (priority == 3 ) $(this).css('color', 'orange');
  else $(this).css('color', 'red');
});

Update: I have revised my answer to ensure that the comparison is made against the first character of each <div>'s content rather than the entire string.

Answer №2

Opt for css classes over Javascript

.red {
    color: red;
 }

 .green {
    color: green;
 }

 .orange {
    color: orange;
 }

Subsequently, within your loop, assess the priority value

<ul id= "list1">
<% todolist.forEach(function(todo, index) { %>
    <li><a href="/todo/supprimer/<%= index %>">✘</a> 
        <%= todo.action %> <%=todo.date%> (priority: 
        <% if (todo.priority <= 2) { %>
            <div id="prio<%index%>" class="green"><%=todo.priority%>/5)</div>
        <% } else if (todo.priority == 3) { %>
            <div id="prio<%index%>" class="orange"><%=todo.priority%>/5)</div>
        <% } else if (todo.priority > 3) { %>
            <div id="prio<%index%>" class="red"><%=todo.priority%>/5)</div>
        <% } %>
    </li>
<% }); %>
</ul>

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

"Alignment problems causing display issues that are not aligning as they

How come my write and check status buttons won't align horizontally with the two divs? I am trying to position the button with id "writeMe" directly to the right of the div with id "test", and then I want the button "statusCheck" to be positioned dir ...

The value of req.user is not defined in a stack involving node, express, passport,

When I use console.log(req.session); I receive the message: Session {cookie:{ path: '/',_expires: null,originalMaxAge: null,httpOnly:true },passport: { user: 5b427a2d117d7c3f6087db8a } } However, when using console.log(req.user); I get un ...

What could be causing the reoccurrence of the error message "JSX is not defined no-undef"?

Encountering an issue while adding a carousel to my home page, I stumbled upon the following error: 'JSX' is not defined. Despite searching on Stack Overflow, GitHub, and Google, the answers provided are similar but I am still unsure of what m ...

Steps for deploying a monorepo using turborepo on Digital Ocean

I am working with a monorepo managed by turborepo. It consists of two packages - 'client' and 'api', located inside packages/* in the root folder. My current challenge is deploying the 'api' package to Digital Ocean, but I&apo ...

Utilizing the parent's background-color in a pseudo-class: A step-by-step

I have a tooltip applied to the .progress element, and the tooltip includes an arrow created using a pseudo-class (:after). I want the arrow to inherit the background color of the tooltip. I am looking for a way to make the child element of <span> i ...

Implementing mouse hover functionality in a VueJS component within a Laravel application

I am facing an issue with my mouse hover functionality while working on Laravel. The Vue file I am using is located in resources/js/Dashboard.vue I have attempted to replace v-on:mouseover with @mouseover but the problem persists. When I hover over the ...

Explain what mongoose and Schema are at the beginning, just once

Hello, I am currently working on a Node.js application using Express and MongoDB. In order to utilize MongoDB and schema, I have to define Mongoose and schema in all of my routing JavaScript files. However, I would like to only define them once. As I am ne ...

Implementing Unicode support in JS/PHP code

I am currently faced with a challenge on my webpage where I utilize JavaScript to transmit data to a PHP script via AJAX POST. The issue arises when the input is in a non-Latin based language, resulting in storing unintelligible characters in the MySQL tab ...

Adjust the color of the text based on a conditional in react

I am looking for a way to select elements and change text color in my unordered list based on specific conditions. Below is an example of the structure I have: <div style={styles.passwordRules}> <ul style={styles.listOne}> <li style={ ...

JavaScript double-click functionality is not operational on IE9 and IE11 browsers

My JavaScript code has an issue where single-click opens a link in a new tab and double-click opens a lightbox. This works perfectly in all browsers except for IE9 and IE11. In my initial code, both single-click and double-click function correctly. However ...

How can you trigger an event when a table cell is selected and a key is pressed?

In my project, I have some td elements with a class name assigned to them. My goal is to trigger a pop-up window when one of these td elements is in focus and the F9 key is pressed. Here's what I've attempted so far: $(document.body).keypress(fu ...

The Bootstrap width is spilling over and not conforming to the content of the form

I'm facing an issue with content overflow on multiple forms within a webpage that uses Bootstrap 4. I can't seem to find a solution to make the width of the forms fit the content properly. Take a look at this picture showing one of the simpler fo ...

Upgrade to the latest Gulp version and transition away from using the gulp.start function

Currently in the process of updating all my gulp v3 projects to v4, but running into an issue with the gulp start function. Upon executing gulp start in gulp v4, I encounter an error. This was the code snippet I used in v3: gulp.parallel within gulp.seri ...

jQuery functionality may be unavailable unless an Alert() is triggered

Hey everyone, I've written some code to generate an HTML table from a JSON file using jQuery. However, the code stops working when I remove the alert() function. Can anyone help me troubleshoot this issue? Thanks in advance! Below is the code snippet ...

The property of undefined map cannot be read

import React from 'react'; import { Card, Text } from "react-native-paper"; import { SafeAreaView, } from "react-native"; class HackerNewsClone extends React.Component { constructor(props) { super(props); this.sta ...

What is the easiest way to import data into a MySQL database table?

Is there a way to move data from a Mysql table or from DataTables to another Mysql table in Laravel? The following code snippet demonstrates the deletion of data from the original table once the transfer is complete. My question is regarding how to incorp ...

I encountered an issue where the variables in my environment files were returning as undefined when I tried to access

After creating my Vue application using vue/cli with the command vue create my-vue, I decided to build the project in next mode. Following the steps outlined in the Vue documentation, I created a .env.next file at the root of the project with the following ...

Control the rules in Jquery.Validate by adding or removing them according to the active tab

I have developed a Bootstrap 4 tabbed interface that includes input boxes on each tab. To enhance user experience, I want to implement different validation requirements for the input fields based on the active tab. Additionally, there are certain mandatory ...

Add elements to an array with express, Node.js, and MongoDB

I'm currently learning about the MERN stack and I'm working on creating users with empty queues to store telephone numbers in E.164 format. My goal is to add and remove these numbers from the queue (type: Array) based on API requests. However, I ...

What is the best way to incorporate a search feature within Bootstrap cards?

I've been struggling to incorporate a search feature within my bootstrap cards. Despite trying various online methods, none have proven successful for me so far. Below is my HTML code - any assistance in implementing a search filter into my app would ...