Home > Mobile >  jquery ui datepicker - beforeShowDay not working when I first open the clendar
jquery ui datepicker - beforeShowDay not working when I first open the clendar

Time:01-10

it looks like the beforeShowDay doesn't work the first time I open the calendar on the current month.

I'm having the jquery ui datepicker with few active days each month. when I refresh the website and open the calendar for the first time, i'll see that all the dates in January are unactive but if I move to February and go back to Jan i'll see the active days (as I should the first time I opened it).

$("#divDatePicker").datepicker({
    dateFormat: 'yy-mm-dd',
    onSelect: function(value, date) { 
        //chose date
        $("#search_term").val( $("#search_term").val()   value );
        $("#divDatePicker").hide(); 
    },
    beforeShowDay: function(d) {        
        var year = d.getFullYear(),
            month = ("0"   (d.getMonth()   1)).slice(-2),
            day = ("0"   (d.getDate())).slice(-2);

        var formatted = year   '-'   month   '-'   day;

        if ($.inArray(formatted, availableDates) != -1) {
            return [true, "","Available"]; 
        } else{
            return [false,"","unAvailable"]; 
        }
    }
});

any ideas?

CodePudding user response:

Consider the following example.

$(function() {

  var availableDates = ["23-01-21", "23-01-22"];

  $("#divDatePicker").datepicker({
    dateFormat: 'yy-mm-dd',
    onSelect: function(value, date) {
      //chose date
      var temp = $("#search_term").val();
      temp  = value;
      $("#search_term").val(temp);
      $("#divDatePicker").hide();
    },
    beforeShowDay: function(d) {
      var formatted = $.datepicker.formatDate("y-mm-dd", d);
      if (availableDates.indexOf(formatted) != -1) {
        return [true, "", "Available"];
      } else {
        return [false, "", "unAvailable"];
      }
    }
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>


<div id="divDatePicker"></div>

<input type="text" id="search_term" />

You can use the utility $.datepicker.formatDate( format, date, options ) to format a Date into a String. You stated you wanted YY-MM-DD, so "23-01-05" for today. This must match with some of your availableDates elements, which I am assuming is an array.

  • Related