Determine whether the last day of the month falls within the designated time frame, and

In my Vue JS application form, I am facing an issue related to the pay frequency <select>. To give some context about the situation, let me explain further.

The application form includes a <select> box with options for users to choose their next pay day, such as Last Working day of the month, Weekly, Bi-weekly, Last Monday of the month, Last Tuesday of the month, and so on. Below, I will list all available options.

Upon selecting an <option>, the system automatically calculates the user's Next & Following pay dates. For example, Next pay: 30/08/2019, Following pay: 27/09/2019. Users also have the flexibility to edit these fields if they wish to do so.

There are 3 input fields for Next pay date and 3 input fields for Following pay date (DD/MM/YYYY).

The problem arises with the pay frequency options for the last week of every month, like Last Monday of the month, Last Tuesday of the month, extending up to Friday. The issue occurs when, let's say, it's the last Thursday of the month, e.g., date is 29/08/2019, and then I select the option Last Monday of the month. Instead of advancing to the next month, it remains in the current month, which is incorrect since Next pay date cannot be in the past.

I am using Moment JS version 2.24.0 and Vue JS version 2.6.10. Additionally, the validation package vee-validate is already set up.

I have various methods in place to determine the user's next and following pay dates. The method payFrequencyChange that I've listed below calculates each available pay frequency option for users to select from. Although I have reviewed the code, it doesn't seem to calculate the month fields correctly based on the date.

Below is the relevant code:


    // Vue instance
    ...

If you execute the above code at the beginning of the month, everything functions perfectly. However, if you change your computer's time/date to, let's say, 29th August 2019, and then select Last Monday - Thursday options, the Next month and Following month fields should increment. But, when choosing Last Friday, it should stay in the current month unless it's 3 days before the end of the month, in which case it should increment as well.

To better understand the scenario, I have prepared a Code Pen demo:

https://codepen.io/sts-ryan-holton/pen/rXGzox

I would appreciate any assistance regarding this matter as I did not write this entirely and am unsure how to resolve or enhance this crucial functionality.

Answer №1

To achieve the desired feature, you can make some adjustments to the lastWeekdayOfMonth function as outlined below:

lastWeekdayOfMonth: function weekly(monthMoment, dayInt) {
    var lastDay = moment(monthMoment).endOf('month').startOf('day')
    var result = this.__lastWeekdayOfMonth(lastDay, dayInt)
    if( result.isBefore(monthMoment) ) {
        lastDay = moment(lastDay).add(1, 'month')
        result = this.__lastWeekdayOfMonth(lastDay, dayInt)
    }
    return result
},
__lastWeekdayOfMonth: function __weekly(lastDay, dayInt) {
    for (let i = 0; i <= 10; i++) {
        if (lastDay.day() === dayInt) {
            return lastDay
        } else {
            lastDay.subtract(1, 'days')
        }
    }
},

I have made the code more modular by introducing an additional function that handles specific tasks.

In addition, I am verifying whether the result is before the specified date and if so, I am checking for the next month.

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

Guide to building a react-redux application with a Node server as the backend

Hey there! I'm looking to build a react-redux app with a node server as the backend. Is it feasible for the node server to serve the react-redux app instead of having react-redux run on one port and node on another? Any suggestions on how to kick thi ...

Utilize Dinero.js to implement currency formatting for input fields in React applications

I am currently working on a form in React that requires certain input fields to be formatted as money currency. These inputs should be prefixed with the dollar sign ($), include commas for thousands separation, and have exactly two decimal points. During ...

Striped shadows in React Three Fiber

Currently in the process of developing a basic 3D object viewer website using Next.js and React-Three-Fiber. Everything was running smoothly until I added a DirectionalLight instance and attempted to make all meshes receive shadows. https://i.sstatic.net/ ...

Leveraging JavaScript along with the jQuery library and API to showcase information related to

Hey there! I have been working on this API that shows upcoming concerts, but I'm struggling to display the images associated with each concert. I've tried using for loops to iterate through the objects, and it seems like every sixth element has ...

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

Secure login system featuring self-contained HTML and Javascript functionalities

I want to create an idle game that will save data on the server instead of using cookies. I am looking for a straightforward method (ideally without using MySQL or PHP) to implement user registration and login functionality using HTML5 and/or Javascript. ...

Utilize the $slots property when working with v-slot in your Vue application

When dealing with a specific use-case, it becomes necessary to retrieve the rendered width and height of a DOM element inside a slot. Typically, this can be achieved by accessing this.$slots.default[0].elm. However, complications arise when introducing sc ...

Cannot locate module required for image change

If I drag the mouse over a flexible component, I want the image to change dynamically. import React, { Component } from "react"; export default class DynamicImageComponent extends React.Component { render() { return ( <img src= ...

The Chrome browser allows interaction between two separate divs, where a button located in one div can impact

One issue I encountered involves a button located within a div that has unintended consequences for another div. Here is the basic structure of the elements: <div> <div> <div> <div> <butto ...

The implicit wait feature in WebDriver JavaScript seems to be ineffective

Waiting for the error message to appear seems to be a bit tricky. I tried using browser.driver.manage().timeouts().implicitlyWait() but had to resort to using browser.driver.sleep() instead. this.getErrorMessage = function () { var defer = protracto ...

Having trouble with Vue JS not showing the footer on your website?

I recently set up vue cli and encountered an issue where my navbar component shows up fine, but the footer component does not display properly. When I navigate to other CMS pages, both the navbar and footer appear together without any text displayed in bet ...

Incorporating Button Value from Anchor Tag Title Upon Page Load

Currently, I am working on a real estate project and facing an issue with a contact modal box. My goal is to extract the title from tag "a" and place it as the button value in the modal box. English isn't my strong suit, so please excuse any errors i ...

When using Next.js to load a client-side library, the component undergoes multiple re-renderings as the state of the parent component changes

On the client side, I am loading the emoji-mart library because it requires the window object. After loading the library, a component is returned. However, when the component is called, it is initially rendered twice and then multiple times as the parent ...

What is the process to set up a WebSocket on Tornado for a production server rather than on a local machine?

Recently, I've delved into the world of WebSockets but have only experimented with them in a localhost environment while developing locally. Following this informative tutorial on real-time data visualization: https://medium.com/@benjaminmbrown/real-t ...

Creating a Singular Instance for Dynamically Loaded Module in Next.js

I'm currently working on creating a Singleton instance for a dynamically imported module in my Next.js app. However, the problem is that each time I call getInstance, it initializes a new instance instead of reusing the existing one. The following co ...

Issue with Backbone.Marionette: jQuery document.ready not executing when on a specific route

I am dealing with a situation in my web application where the document.ready() block is not being executed when the page routes from the login button to the dashboard. I have an initialize() function that contains this block, but it seems like there is an ...

I have successfully resolved the CORS issue on my NodeJS application, but unfortunately, I am encountering errors when trying to fetch APIs on my React and JavaScript projects

Sample Code: const express = require('express'); const port = 3000; const router = express(); router.get('/', (req, res) => { res.send('Hi'); }) var request = require('request'); var options = { 'me ...

When the background image URL is altered, the button size automatically adjusts

Presently, I am working with a button <input id="fireAction" type="button" class="submit" onclick="disableSubmit('preFlight');"><br> Afterwards, I modify the background image of the button under different circumstances For example ...

The Django image upload is not successful when attempting to use JavaScript from a string of markup code

I have successfully implemented django dynamic forms that work upon clicking, but I am facing an issue with uploading images. I made sure to include request.FILES and added enctype="multipart/form-data", however, the image upload still doesn't seem t ...

Avoid activating jQuery functions based on certain screen widths for menu/navigation system

Recently, I've delved into the world of jQuery and attempted to create a simple menu system. The menu is designed to expand its submenu when hovering over the list item at screen widths larger than 480px, and to expand when clicking on the list item a ...