March 15, 2012

Jquery Datepicker add 2 years to year not based on month/day

Question by user1272083

I have implemented the jQuery datepicker to allow the selection of dates on a form, it should allow the selection of date based on the current date + 2 years however in the final year it will not proceed past the current date or month.

As such if today is 15/03/2012 the maximum available date would be 15/03/14. However, I require the entire of 2014 to be selectable. As such, the maximum should be 31/12/14.

How would I best go about this to enable it to auto update as it currently does?

<script type="text/javascript">
    <!-- 
         $(function() {
           $('.datepicker').datepicker({
                numberOfMonths: 3,
                showButtonPanel: true,
                defaultDate: "+1w",
                changeMonth: true,
                changeYear: true,
                numberOfMonths: 3,
                minDate: "-0",
                maxDate: "2y",
                dateFormat: 'dd-mm-yy'
    });
    });
    -->

Answer by Starx

Use yearRange options. Use it like

yearRange: 'c:c+2'

Here, c represnts current year and c+2 the next two years.

$('.datepicker').datepicker({
    numberOfMonths: 3,
    showButtonPanel: true,
    defaultDate: "+1w",
    changeMonth: true,
    changeYear: true,
    numberOfMonths: 3,
    yearRange: 'c:c+2',
    dateFormat: 'dd-mm-yy'
});

Here is a demo for the above example.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!