"Using Javascript to assign a class based on a date being greater than

I am facing an issue with a script that applies a CSS class to table cells if the date is greater than a certain value. Currently, the script only works for today's date. I need it to work for dates within and outside of this week as well.

$('td:nth-child(7)').each(function() {

        var today = new Date();
        var week = new Date();
        var dd = today.getDate();
        var ddd = today.getDate()+7;
        var mm = today.getMonth()+1;
        var yyyy = today.getFullYear();

        if(dd<10) {
            dd = '0'+dd
        } 

        if(mm<10) {
            mm = '0'+mm
        } 

        today = dd + '/' + mm + '/' + yyyy;

        if ($(this).text() == today) {
            $(this).closest("td").addClass("red");
        }
        if ($(this).text() < today + 7 && $(this).text() != today ) {
            $(this).closest("td").addClass("yellow");
        }
        if ($(this).text() > today + 7) {
            $(this).closest("td").addClass("green");
        }
    });

Answer №1

give this a shot

    let currentDate = new Date($(this).text());
    let tomorrow = new Date();
    if (currentDate > tomorrow.setDate(tomorrow.getDate() + 7)) {
      // the current date is more than 7 days ahead of tomorrow

    }

Answer №2

Make sure to compare dates, not just strings. It's important to convert the date into a Date object before comparing.

For equality comparisons, use valueOf() to ensure accurate results without relying on reference comparison.

Check out this example code snippet:

$('td').each(function() {

  var today = new Date();
  today.setHours(0,0,0,0);
  
  var nextWeek = new Date(today);
  nextWeek.setDate(nextWeek.getDate() + 7);
  
  var cellDateParts = $(this).text().split("/");
  var cellDate = new Date(cellDateParts[2], parseInt(cellDateParts[1]) - 1, cellDateParts[0]);
  
  if (cellDate.valueOf() === today.valueOf()) {
    $(this).closest("td").addClass("red");
  } else if (cellDate < nextWeek) {
    $(this).closest("td").addClass("yellow");
  } else if (cellDate > nextWeek) {
    $(this).closest("td").addClass("green");
  }
});
.red {
  background: red;
}

.yellow {
  background: yellow;
}

.green {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <td>07/07/2017</td>
  <td>07/08/2017</td>
  <td>23/07/2017</td>
</table>

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 best way to transform a string into an array?

After receiving an object from the http response, it looks something like this: {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] } The key in the object is represented as an array. Is there a method in ...

My tests are not passing because I included a compare method in the Array prototype. What steps can I take to fix this issue in either the

Embarking on the challenging Mars Rover Kata has presented a unique problem for me. My jasmine tests are failing because of my array compare method within the prototype. This method is crucial for detecting obstacles at specific grid points. For instance, ...

Discovering a CSS value using jQueryUncovering the CSS value with jQuery

Currently, I have a script that allows me to change the color of an event in a calendar to red when clicked. eventClick: function(calEvent, jsEvent, view) { $(this).css('border-color', 'red'); } Now, I want to enhance this featur ...

Preserve the content in the text box corresponding to the selected radio button

In my form, there are multiple radio buttons, each with an associated text box value. Users can only select one radio button at a time and submit the form. However, sometimes users will enter data in a textbox for one radio button, then switch to another o ...

Discover the power of utilizing the reduce function to extract the value of a specific field within an array of Objects

In the following example, we have an object with 3 forms: formA, formB, and formC. Form A and B are objects, while formC is an array of objects that can contain multiple items. const object: { "formA": { "details": {}, ...

Step-by-step guide on how to change the appearance of a <DIV> using data from a database (JSON

After retrieving data from a database as a JSON file, I have written code to loop through an item (portOn) and determine if certain ports are present in the array. If a port is found in the array, its corresponding variable is set to true. var portG01,port ...

Experience a glint in the React Suspense with React Router - Struggling with CSS properties post utilizing Suspense and Lazy

I'm experiencing an issue with my code where the CSS properties are not working properly when I wrap the code in suspense. The page loads and the suspense functions as expected, but the styling is not being applied. However, if I remove the suspense, ...

Tips for achieving a unique look with CSS: Transforming border radius colors in four distinct sections

Is it possible to create a gradient border with multiple colors using border radius? div { border-radius: 30px; width: 60px; height: 60px; border: 1px red solid } Hello <div> </div> I am looking to achieve a unique effect on my bord ...

Issue with bottom margins or padding

I am a beginner and I have noticed some black space at the bottom of my page. Unfortunately, using margin-bottom to remove it doesn't work as expected. When scrolling down, there is this pesky black space that I want to get rid of. Any help would be a ...

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

recursive algorithm utilizing an array as an argument

Currently, I am in the process of developing a function that extracts chest exercises from an array titled "chest". This particular function is required to randomly select multiple exercises, achieved by utilizing a random pointer. In order to avoid selec ...

Arranging a JSON Object Array in JavaScript by its alphanumeric key attribute order

I need assistance sorting this JSON array by unitId var array = [ { id: 10, unitId: 'unit17' }, { id: 11, unitId: 'unit19' }, { id: 13, unitId: 'unit27' }, { id: 12, unitId: 'unit2' }, { id: 13, unitId: 'unit ...

Struggling to make css selector acknowledge the margins on the right and left

I am trying to style two inner divs within a containing div by floating the first one to the left and the second one to the right. Additionally, I want to add a margin of 15px on the left for the first div and on the right for the second div. The challenge ...

Modify top position without affecting bottom alignment using CSS

I am currently working on a website that is designed to mimic a printable document. The layout consists of a header, body, and footer, with each element utilizing CSS for margin and height adjustments. The challenge lies in ensuring that the footer is alw ...

Utilize duplicate named CSS grid rows as a reference

Summary; This method currently works, but it requires adding multiple nth-child selectors for each new person and their answer. I am seeking a solution that can dynamically handle any number of rows using an even and odd selector to simplify the process. ...

unable to call the anonymous inline onclick method of JavaScript

In my HTML file, I have the following code: <a onclick="getRestaurantTime({{ $afternoonTiming[$j]->id}});">Hello</a> Furthermore, I have an anonymous function in restaurant.js file: var Restaurant = (function ($) { function getRestaur ...

Display a div element using AngularJS

Looking for a way to display a div using AngularJS, I came across some solutions on StackOverflow. However, implementing them did not work in my case. Here is my HTML code: <div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue" clas ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

Ensure that the navbar remains within the container as you scroll down the page

With the implementation of bootstrap 4, I have successfully integrated a fixed navbar inside a container. Initially, at the top of the page, it occupies the full width, but as soon as I start scrolling, it smoothly transitions into the confines of the cont ...