I'm a bit desesperate as I don't understand why beforeShowDay doesn't work the way I expect it to work. I'm trying to highlight some date that comes from a database (I get the data from Ajax)
I can't seems to make it work, the date never highlight even if I try different date format
In the html part, I call the calendar like this :
<div class="calendar" id="Date" ></div>
For the Ajax part, I get my date array like this :
var days_custom = [];
URL = 'get_date.php';
$.ajax({
type: "GET",
url: URL,
dataType: 'json',
success: function(data) {
for (var t in data) {
days_custom[days_custom.length] = data[t].date
}
console.log(days_custom);
}
});
and in the console, I see my dates with that format:
['2024-05-05', '2024-05-07', '2024-05-08', '2024-05-09', '2024-05-11', '2024-05-12', '2024-05-13', '2024-05-14', '2024-05-15', '2024-05-17', …]
My next step is to uses those date to try to change the backgound color and have an highlight for those specific date :
$("#Date").datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: function(date) {
t_date = $.datepicker.formatDate('yyyy-mm-dd', date);
if (days_custom.indexOf(t_date) > -1) {
return [true, 'event', 'test highlight'];
}
return [true];
}
});
In my css file, I have this :
.event a {
background-color: #5FBA7D !important;
color: #ffffff !important;
}```
And this does nothing.
I also tried to write in the console in the beforeShowDay function, but nothing appears, so I even wonder if I get in this in the code...
Also, I tried to destroy the datepicker just before the code, as I saw that on another question but it's not my issue, so I removed it from the code because it didn't change anything.
Thanks for the help guys
The issue is that you have the incorrect date format in the beforeShowDay function.
you have:
t_date = $.datepicker.formatDate('yyyy-mm-dd', date);
which makes a date like this '20242024-11-08'
You need to update your code so it has a date format like this:
t_date = $.datepicker.formatDate('yy-mm-dd', date);
This will give you the correct date format '2024-11-08'
I have written a snippet below that uses a hard coded date array instead of ajax and made the dates in November so its easier to see. Try run it yourself and see the results.
var days_custom = ['2024-11-05', '2024-11-07', '2024-11-08', '2024-11-09', '2024-11-11', '2024-11-12', '2024-11-13', '2024-11-14', '2024-11-15', '2024-11-17'];
$("#Date").datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: function(date) {
t_date = $.datepicker.formatDate('yy-mm-dd', date);
if (days_custom.indexOf(t_date) > -1) {
return [true, 'event', 'test highlight'];
}
return [true];
}
});
.event a {
background-color: #5FBA7D !important;
color: #ffffff !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.14.1/jquery-ui.min.js" integrity="sha256-AlTido85uXPlSyyaZNsjJXeCs07eSv3r43kyCVc8ChI=" crossorigin="anonymous"></script>
<div class="calendar" id="Date" ></div>