Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

79
Views
How to increment value in the object Date each time by click event using JavaScript?

I wanna change the date object every time when I'm clicking the button. I'm trying to handle it using the following function:

.on('click', '.change-date-button', function () {
    Date.prototype.addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
    }
    var date = new Date();
    console.log(date.addDays(3));
}

But as result, I get the same object. How to increment and decrement the date object in the correct way and get a new date added seven days every time by click? As an example, I get 18/07/2022 several times, however, I need to get 21/07/2022, 24/07/22, etc... by the next click.

7 months ago · Santiago Gelvez
2 answers
Answer question

0

It is a bad idea to redefine a method on a prototype at each click of a button. You might as well just do the job inline -- without any function.

Also, your function explicitly does the job of not changing the date, but returning a new one, and the function is always called with today's date and time -- at every click.

You refer to "the date object" as a global object, but then you need to create it as a global:

var date = new Date(); // <-- outside handler scope
// ...

$(document).on('click', '.change-date-button', function () {
    date.setDate(date.getDate() + 3);
    console.log(date);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="change-date-button">Add three days</button>

7 months ago · Santiago Gelvez Report

0

An alternative is to use the date-fns library, because in this case you wouldn't need to redo something that already exists in a simplified way.

https://date-fns.org/v2.28.0/docs/add

7 months ago · Santiago Gelvez Report
Answer question
Find remote jobs