Search code examples
javascriptjquerydatetimepicker

Jquery date picker select highlighted month


I have a datepicker and here i highlight selected period.But i have some issue here,that is This is January 2017 But when i select some period of february then It's correctly highlighted in february but Default it shows current month int datepicker that is January.

Code

$("#daterangepicker1").datepicker({
  inline: true,
  beforeShowDay: function(date) {
    var theday = (date.getMonth() + 1) + '/' +
      date.getDate() + '/' +
      date.getFullYear();
    return [true, $.inArray(theday, dtrange) >= 0 ? "hightlight" : ''];
  }
});

Solution

  • If you need to open the jQuery Date picker from a specific month, you need to set the defaultDate of the date picker. For your requirement you need to set any day of February to be the default date of the date picker. Here is a sample code snippet. Here it sets 3 days of February to be default selected and sets first of February to be the default date. Hence your calendar opens from February 2017.

    Here is a sample snippet

    <!doctype html>
    <html lang="en">
    
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>jQuery UI Datepicker - Default functionality</title>
        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <style>
            .hightlight {
                background: green;
            }
        </style>
        <script>
            $(function () {
                $("#daterangepicker1").datepicker({
                    inline: true,
                    defaultDate: new Date("2/1/2017"),
                    beforeShowDay: function (date) {
                        var dtrange = ["2/2/2017", "2/12/2017", "2/22/2017"];
                        var theday = (date.getMonth() + 1) + '/' +
                            date.getDate() + '/' +
                            date.getFullYear();
                        return [true, $.inArray(theday, dtrange) >= 0 ? "hightlight" : ''];
                    }
                });
            });
        </script>
    </head>
    
    <body>
    
        <p>Date:
            <input type="text" id="daterangepicker1">
        </p>
    
    
    </body>
    
    </html>