• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

155
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.

almost 3 years 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>

almost 3 years 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

almost 3 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error