Developer
Developer

Reputation: 1437

how to set -3years from current date and +9months from the current date in JQUERY in datepicker

enter image description here

Hey Iam using html5 date attribute and it needs some Restriction from past Year And Future Dates Dynamically by having todays current date / year.

DEMO

Example :

current year is 2015-3 = 2012 + 9 months

JS :

var checkUserAgent = navigator.userAgent;
      // if (checkUserAgent.match(/iPad/i) || checkUserAgent.match(/iPhone/i)) {
            $('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');
            var checkBabyId1 = $('#babys_due_date_id').length > 0;
            if (checkBabyId1 == true) {

                // logic for 9 months 
                var myMonths = 9;
                var CurrentDate = new Date();
                CurrentDate.setMonth(CurrentDate.getMonth() + myMonths);

                console.log(CurrentDate) // adding 9 months 

                // logic for - 3 years
                var myPastYears = 3;
                var CurrentYear = new Date();
                CurrentYear.setYear(CurrentYear.getYear() - myPastYears )
                console.log(CurrentYear) // - 3years


                $('#ui-datepicker-div').hide();
                $('#babys_due_date_id.date-padding label').hide();
                $('#babys_due_date_id')
                .find('input')
                .prop({
                    /*'readonly':'true', */
                    'type':'date'/*,
                    'min' : '2012-01-01',
                    'max' : '2016-12-01'*/
                })
                .css({ 
                    'border':'1px solid #f00 !important',
                    'width':'200px','margin-top':'10px' 
                });

                $('#babys_due_date_id label').on('click', function(e){
                    e.preventDefault();
                    $('#ui-datepicker-div').hide();
                });

                $('#babys_due_date_id-datepicker-popup-0').on('click', function(){
                    $('#ui-datepicker-div').remove();
                    $('#ui-datepicker-div').datepicker( "option", "disabled", true );
                });
            }
      // }

Upvotes: 0

Views: 683

Answers (1)

ronhippler
ronhippler

Reputation: 106

use the minDate option:

$('#ui-datepicker-div').datepicker( "option", "minDate", "-3y +9m");

http://api.jqueryui.com/datepicker/#option-minDate

or:

<script>
  var now = new Date();
    var year = now.getFullYear() - 3;
    var month = now.getMonth() - 8; // jan = 0
    if (month < 0) {
      month = 11 + month;
      year++;
    }

  $('#datepicker').attr("min", year+'/'+month+'/'+now.getDate());
</script>

for simple <input type="date">

Upvotes: 1

Related Questions