Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight specific dates in Jquery UI Datepicker

I've read the other questions like this here, but none does exactly what I want.

I want to add a class to all the days between two dates. The dates will be set in variables.

Any thoughts?

like image 301
Spoeken Avatar asked Apr 16 '12 11:04

Spoeken


People also ask

How do I highlight specific dates in jquery ui Datepicker?

Define beforeShowDay within datepicker() method. In the function create a new date format according to the defined format (dd-mm-yyyy) in an Array. Check for the date in the Array with $. inArray() method if it is available then return [true, "highlight", tooltip_text]; otherwise return [true] .

How to display selected date in Datepicker jQuery?

$(function() { $("#datepicker"). datepicker({ dateFormat: "yy-mm-dd", onSelect: function(){ var selected = $(this). datepicker("getDate"); alert(selected); } }); });

How do I highlight today's date in bootstrap Datepicker?

todayBtn. If true or “linked”, displays a “Today” button at the bottom of the datepicker to select the current date.


1 Answers

You need to implement the beforeShowDay event for the datepicker:

The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, [1] equal to a CSS class name(s) or '' for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the datepicker before it is displayed.

So you need to do something like:

$("#datepicker").datepicker({
    beforeShowDay: function(d) {
        var a = new Date(2012, 3, 10); // April 10, 2012
        var b = new Date(2012, 3, 20); // April 20, 2012
        return [true, a <= d && d <= b ? "my-class" : ""];
    }
});

Demo:

$(function() {
  $("#datepicker").datepicker({
    beforeShowDay: function(d) {
      // a and b are set to today ± 5 days for demonstration
      var a = new Date();
      var b = new Date();
      a.setDate(a.getDate() - 5);
      b.setDate(b.getDate() + 5);
      return [true, a <= d && d <= b ? "my-class" : ""];
    }
  });
});
@import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/blitzer/jquery-ui.min.css");

.my-class a {
  background: #FC0 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<input id="datepicker">

Another demo here

like image 165
Salman A Avatar answered Sep 21 '22 15:09

Salman A