Johan
Johan

Reputation: 211

datepicker dynamic date button

I am trying to create a custom dynamical date extra button in jquery datepicker. But it doesnt work... Error in my code?

$(function () {
    $(".datepicker").datepicker({
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear: true,
        yearRange: "2014:2034",
        showButtonPanel: true,
        beforeShow: function (input) {
            setTimeout(function () {
                var buttonPane = $(input)
                    .datepicker("widget")
                    .find(".ui-datepicker-buttonpane");

                var btn = $('<button class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" type="button">CSA</button>');
                btn.unbind("click")
                    .bind("click", function () {
                        //$.datepicker._clearDate(input);
                        //alert('custom text');
                        $(input).datepicker("hide");
                        var date = new Date();
                        date.setMonth(date.getMonth() + 6);
                        $(input).val(date.getFullYear() + '-'
                            date.getMonth() + '-' + date.getDate());

                    });


                btn.appendTo(buttonPane);

            }, 1);
        }
    });
});

the goal is to add a button today + 6 months

Upvotes: 0

Views: 82

Answers (1)

Emil Borconi
Emil Borconi

Reputation: 3467

You are missing a +

Change this:

       $(input).val(date.getFullYear() + '-'
       date.getMonth() + '-' + date.getDate());

To this:

       $(input).val(date.getFullYear() + '-' +
       date.getMonth() + '-' + date.getDate());

Also do not forget that Javascript moth is 0 based, so if you want to add 6 month to today's date you need to add 7 to current month, meaning, instead of:

date.setMonth(date.getMonth() + 6);

use:

date.setMonth(date.getMonth() + 7);

See example here

Upvotes: 2

Related Questions