Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading