简体   繁体   中英

User select date 10 years from today date jquery datepicker

Working on jquery date picker in my current code. I want the datepicker should show from the year 1900 - till today date User has to select previous 10 years from today date if in case user select yesterday date or today 's date or a month ago date eror msg should populate in the error message field

Here is my current Jquery code

$(function() {
    $( "#datepicker" ).datepicker({
          changeMonth: true,
          changeYear: true,
        yearRange: '-115:+1M'
    }).on('change',function(){
        alert("check");
    });
 });

Here is the fiddle Link

Kindly help me

Thanks & Regards Mahadevan

You can do all the calculations in the onSelect:fn(){} provided by the the datepicker itself. You can get the selected value from the function's param name of your choice, i have given it the name date . Now when you get the date from here you can convert it to a dateObject to extract the year from it, same way you need to get the current year with a new date object.

 $(function() { $("#datepicker").datepicker({ changeMonth: true, changeYear: true, yearRange: '-115:+0M', onSelect: function(date) { // bind the builtin onSelect event // which gets you the selected date var selYear = new Date(date).getFullYear(); // get the full year of selected date var currYear = new Date().getFullYear(); // get the current year if ((currYear - selYear) > 10) { // check in the if conditon for 10 years $('#display_error').html('You should choose dates from last 10 years only.'); this.value=''; } } }); }); 
 <link href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <p>Date: <input type="text" id="datepicker"> </p> <label id="display_error" class="display_error"></label> 

ok Try this fiddle http://jsfiddle.net/bxh5eq1f/

It is WORKING

Javascript

$(function() {
        $( "#datepicker" ).datepicker({
              changeMonth: true,
              changeYear: true,
            yearRange: '-115:+1M',
            maxDate:new Date(),
        }).on('change',function(){
            today = new Date();
            tenYearBefore = new Date().setYear(new Date().getFullYear() -10);
            selected = new Date($(this).val());
           if(selected>tenYearBefore) {
            $(".display_error").show();   
           } else {
               $(".display_error").hide();
           }
        });
  });

let me know if it is worked

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