"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

Unable to make colors appear in HTML5 canvas using .fillStyle

Trying my hand at canvas for the first time to create a game. I have an image displaying, but strangely the fillStyle method doesn't seem to be working as expected (the canvas background remains white in Google Chrome). Just a note that in my code, t ...

Maintaining Style Values with jQuery While Navigating Back

I am facing an issue with maintaining the style value when returning to a page from another. My jQuery code is responsible for displaying my menu. $( "#burger" ).click(function() { if ($("#burger").hasClass("closed")) { $( "#menu" ).animate({ ...

Difficulty encountered while implementing the if-else statement in raycasting operations

Currently, I am experimenting with raycasting to determine if my mouse is pointing at an object. The function seems to be working fine when the object is not being touched - it correctly prints out "didnt touch". However, when the object is touched, it s ...

It is important for the button size to remain consistent, regardless of any increase in text content

My goal was to keep the button size fixed, even as the text on it grows. This is the current code I am using: .button { border: none; color: white; padding: 10px 50px; text-align: center; text-decoration: none; display: inline-block; font ...

What is the best way to retrieve information from a webpage I have created using an express backend and an HTML frontend

I designed a login page named index.html that prompts users to enter their email and password, followed by a submit button with the label "Log In": <input type="submit" value="Log In" id="loginbutton"> Within my app.js ...

In my development environment, the page does not have scroll functionality, but in the production environment, it is scrollable

Whenever I open a table or any other element with overflowing content, I encounter an issue with the scrolling bar. Even though the CSS includes overflow-y: scroll;, the scroll bar on the right remains in gray and does not allow me to scroll down when the ...

Is it possible to switch the linter in grunt.js to jslint instead?

Is it feasible to switch the linter used by grunt.js from jshint to jslint, considering that I am more accustomed to using jslint over jshint as the default linter? ...

Create a sleek and innovative tree user interface in a single line with the power of Angular and fxF

I created a tree with parent and child nodes, but I'm facing an issue where the positions of the checkboxes are not aligned in a straight line. Here is my code snippet: <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle> ...

The functionality of Node.js's hasOwnProperty method fails to return true even for existing properties

When a user logs into my Node.js Express application using Passport, their user object is saved in the request. Here is an example of what the user object may look like: { "uuid": "caa5cb58-ef92-4de5-a419-ef1478b05dad", "first_name": ...

Fulfill all of the promises within Bluebird, as well as decline any that do

I am in search of a method to retrieve both successful resolutions and rejections from a promise array. I am relying on the Bluebird implementation, so any ES6 compatible solution would be preferable. One option that comes to mind is utilizing Bluebird&ap ...

Arrange the HTML elements in a line, one following the next

I need assistance with aligning two dropdown lists in the jsbin provided. How can I position them one after the other, center them on the page, and ensure there is enough space between the two elements without manually adding spaces using   In additi ...

The issue of req.file being undefined when using Multer in Node.js with Express Router

I have been working on incorporating File Upload capability utilizing multer and Express Router. I set up an endpoint /batch_upload using router.use in the following manner: api.js router.use( "/batch_upload", upload.single("emp_csv_data"), userCo ...

Design a CSS floating div with a captivating bubble effect

My current setup includes a DIV element styled as follows: <div class="modal"></div> .modal { position: fixed; z-index: 999999; right: 310px; top: 67px; width: 431.6px; height: 550px; border-radius: 25px; box-s ...

Position child divs at the center of the parent div

I am struggling to center 3 child divs inside a parent div that must remain at a width of 100%. Can someone help me figure out how to achieve this? .parent { width: 100%; border: 1px solid blue; } .child { float: left; borde ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

Creating HTML tabs using jQuery with input[type="radio"] tutorial for beginners

I'm having trouble creating a tab with input[type="radio"] using Jquery. The tab works fine on the first click, but it doesn't work on the second click. I can't figure out where the issue is in the Jquery code. Can someone assist m ...

Unexpectedly, CSS is failing to override React-Bootstrap and Bootstrap as intended

Currently, I am tackling a project that involves utilizing react-bootstrap along with my own custom CSS for styling. Both are imported in my index.js file as shown below: import React from 'react'; import ReactDOM from 'react-dom'; impo ...

How to Implement Autocomplete Feature in Angular

CSS <div class="dropdown"> <input type="text" formControlName="itemName" (ngModelChange)="filterItems()" class="dropdown-input" (keyup)="onKeyPress($event)" (blur)="toggleDropdown(0)" (focus)="toggleDropdown(1)" placeholder="Search..." [ngCla ...

How to retrieve the $0 element using Python Selenium

There is an unnamed element I can only access with a dollar sign: console.log($0); "100" In Python Selenium, how can I retrieve this element? I attempted the following: my_value=driver.find_element(By.NAME,"$0") However, it resulted i ...

How can we incorporate dynamic HTML elements into a React JS application?

My code seems to be having an issue. I'm working on a registration form and trying to include an error message if the passwords entered do not match. For some reason, I am unable to dynamically add a para tag to my HTML. Any insights on why this could ...