I have a Jquery datepicker where I list all holidays and display the name of each holiday in a tooltip during hover effect. But I'm facing a bug, everything works normally when I use a for loop to display my tooltip, but when I try to use $.each() my tooltip doesn't work, here's my code:
$(".datepicker").datepicker({
dateFormat: 'dd/mm/yy',
beforeShowDay: function(d) {
var dmy = "";
dmy += ("00" + d.getDate()).slice(-2) + "-";
dmy += ("00" + (d.getMonth() + 1)).slice(-2) + "-";
dmy += d.getFullYear();
if ($.inArray(dmy, enableDays) >= 0) {
$.each(data, function (index, item) {
if(item.date == dmy){
console.log('forEach: ', item)
return [true, 'highlight', item.name];
}
})
/*
for (var i = 0; i < data.length; i++) {
if (data[i].date == dmy) {
console.log('for: ', data[i])
return [true, 'highlight', data[i].name];
}
}
*/
return [true, ''];
}
else {
return [false, ""];
}
}
});
This what my $.each() returns in the console with the names of the holidays, it went through three times.

And this is what the console returns when I use the for loop:
To put it simple:
return inside a for loop will stop execution and exit the function with that returned value ([true, 'highlight', item.name] in your case) — which BTW is expected for the beforeShowDay function to return with an array to work properly.
jQuery's $.each(iterable, callback(index[, item])), will iterate over all the iterable set (Array) without stopping unless you use return false;.
The returned array you're using is enclosed inside its own callback scope — but not in the outer beforeShowDay function scope. Therefore you see all the logs, but the $.each didn't stopped with a return that would ultimately exit the beforeShowDay function. It ultimately always exits with the return [true, ''] Array.
To make it work with a $.each use:
let result = [true, ""]; // Default
$.each(data, function (index, item) {
if (item.date == dmy) {
result = [true, 'highlight', item.name]; // Modify it!
return false; // Exit $.each loop
}
});
return result; // Return Default or Modified
Here's the above implemented in your example:
$(".datepicker").datepicker({
dateFormat: 'dd/mm/yy',
beforeShowDay: function(d) {
var dmy = "";
dmy += ("00" + d.getDate()).slice(-2) + "-";
dmy += ("00" + (d.getMonth() + 1)).slice(-2) + "-";
dmy += d.getFullYear();
if ($.inArray(dmy, enableDays) >= 0) {
let result = [true, ""]; // Default
$.each(data, function (index, item) {
if (item.date == dmy) {
result = [true, 'highlight', item.name]; // Modify it!
return false; // Exit $.each loop
}
});
return result; // Return Default or Modified
} else {
return [false, ""];
}
}
});