简体   繁体   中英

Increase or decrease value using jquery

I have a javascript variable which is the day number of current date.

I wanted to give the user to go to previous date by clicking on a button.

Here's the fiddle .

Tried googling but I didn't understand or anything did help me.

I'm able to decrease just one day by giving -1 in the day variable. But I couldn't figure out how to decrease it on each click.

Someone help me in how can I decrease and increase the date of click of those buttons?

Thanks in advance.

There are a couple of problems in your code. The major one being that you create a new date Object on every button click with the current date. That's why you're getting the same result every time.

If you just want to add or remove one day from the date you could do just this:

var currentDate = new Date();    
$('button').click(function() {
    var add = $(this).hasClass('increase_date') ? 1 : -1;
    currentDate.setDate(currentDate.getDate()+add);
    $('.display_date').html(currentDate);    
})

http://jsfiddle.net/3VQZy/

Store your current date in a global variable & use -= operator on it do decrese it by one using current value.

Something like this http://jsfiddle.net/SYRDR/2/ I only show how to decrease it, you have to add further conditions to formatt date properly

demo: http://jsfiddle.net/SYRDR/14/

$(document).ready(function() {
        showDate(0);
        $('.decrease_date').click(function() {
            showDate(-1);        
        });
        $('.increase_date').click(function() {
            showDate(1);        
        });
    })

    function showDate(change)
    {
        var current_date;    
        if(change == 0)
        {
            current_date = new Date();
        }
        else
        {
            current_date = new Date($('.display_date').html());
        }        
            var year = current_date.getFullYear();
            var month = "0" + (current_date.getMonth() + 1);
            var day = current_date.getDate();

        if(change == -1)
        {
            day = day - 1;
        }    
        if(change == 1)
        {
            day = day + 1;
        }
            var start_date2 = year + "-" + month + "-" + day;        
            $('.display_date').html(start_date2);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM