Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k

Highlight days in array in jquery ui calendar

Jan 23 2023 2:27 PM

Ok, so I have a calendar and I want to highlight specific days that come from a json

Jquery calendar

<script>
    $( document ).ready(function() {
        $.getJSON(`?handler=LoadDaysCMP`, (data) => {
            dates = [];
            data.forEach(function(i,v){
            dates.push((new Date(i)).setHours(0,0,0,0).valueOf());
            })
        });
    });
    $(function () {
        $.datepicker.regional['ro'] = {
            closeText: 'Inchide', // set a close button text
            currentText: 'Astazi', // set today text
            monthNames: ['Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie', 'Iulie', 'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie'], // set month names
            monthNamesShort: ['Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Iun', 'Iul', 'Aug', 'Sep', 'Oct', 'Noi', 'Dec'], // set short month names
            dayNames: ['Duminica', 'Luni', 'Marti', 'Miercuri', 'Joi', 'Vineri', 'Sambata'], // set days names
            dayNamesShort: ['Dum', 'Lun', 'Mar', 'Mie', 'Joi', 'Vin', 'Sam'], // set short day names
            dayNamesMin: ['Du', 'Lu', 'Ma', 'Mi', 'Jo', 'Vi', 'Sa'], // set more short days names
            dateFormat: 'dd/mm/yy' // set format date
        };

        $.datepicker.setDefaults($.datepicker.regional['ro']);


        $("#datepicker").datepicker({
            firstDay: 1,
            dateFormat: "yy-mm-dd",
            onSelect: function () {
            var selected = $(this).val();
            $("#dataSelect").val(selected);
            }
        });
    });

</script>
JavaScript

json

public async Task<JsonResult> OnGetLoadDaysCMPAsync()
{
    var data = await _context.CMPAvDates.Select(s => s.CMPDate).ToListAsync();
    return new JsonResult(data);
}
C#

but how do I highlight days from json in calendar?


Answers (13)

5
Naimish Makwana

Naimish Makwana

  • 140
  • 13.5k
  • 184.2k
Jan 24 2023 7:13 AM

Try below code with your date formate. 

<!-- Using latest jQuery, and jQuery UI -->
var highlight_dates = ['2023-01-25T00:00:00','2023-01-24T00:00:00','2023-01-26T00:00:00']; 
$(function() {
$('#datepicker').datepicker({
  dateFormat: 'yyyy-mm-dd',
       beforeShowDay: function(date){
           var month = (date.getMonth() + 1).toString().padStart(2, "0");
           var year = date.getFullYear();
           var day = date.getDate().toString().padStart(2, "0");

           // Change format of date
           var newdate = year+"-"+month+'-'+day+'T00:00:00';
console.log(newdate)
           // Check date in Array
           if(jQuery.inArray(newdate, highlight_dates) != -1){
                // Pass class name and tooltip text
                return [true, "highlight"];
           }
           return [true];
       }
   });
});

Please accept answer if its useful.

Thanks

Accepted Answer
3
Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k
Jan 24 2023 8:30 AM

Final working script, also with disabling weekend 

<script>
        $(document).ready(function() {
            
            var unavDates = new Array();
            $.getJSON(`?handler=LoadDaysCMP`, (data) => {
                for (var i in data) {
                    unavDates.push(data[i]);
                }
            });

            $(function(){
                $("#datepicker").datepicker({
                    firstDay: 1,
                    dateFormat: "yy-mm-dd",
                    beforeShowDay: function (date) {

                        var month = (date.getMonth() + 1).toString().padStart(2, "0");
                        var year = date.getFullYear();
                        var day = date.getDate().toString().padStart(2, "0");

                        // Change format of date
                        var newdate = year + "-" + month + '-' + day + 'T00:00:00';
                        // Check date in Array
                        if (jQuery.inArray(newdate, unavDates) != -1) {
                            return [true, "highlight"];
                        }
                        if (date.getDay() === 0 || date.getDay() === 6){
                            return false;
                        }

                        return [true];
                    },
                    onSelect: function () {
                        var selected = $(this).val();
                        $("#dataSelect").val(selected);
                    }
                });
            });
            debugger;
        });
    </script>

 

3
Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k
Jan 24 2023 7:23 AM

Thank you Naimish, that worked.

3
Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k
Jan 24 2023 7:04 AM

Thank you Naimish, they way you have it works but my json does not give me dates in that format. Result from json is

2023-01-25T00:00:00,2023-01-24T00:00:00,2023-01-26T00:00:00 (yy-mm-dd)

btw, when I tried

var highlight_dates = ['2023-01-24T00:00:00', '2023-01-26T00:00:00', '2023-01-25T00:00:00'];
                        
                        var year = date.getFullYear();
                        var month = date.getMonth() + 1;
                        var day = date.getDate();

                        // Change format of date
                        var newdate = year + "-" + month + '-' + day + 'T00:00:00';

                        // Check date in Array
                        if (jQuery.inArray(newdate, highlight_dates) != -1) {
                            return [true, "highlight"];
                        }
                        return [true];

was not working. Why?

3
Naimish Makwana

Naimish Makwana

  • 140
  • 13.5k
  • 184.2k
Jan 24 2023 6:37 AM

Hello Marrius,

Below is working code. Please check.

<!-- Using latest jQuery, and jQuery UI -->
var highlight_dates = ['8-11-2022T00:00:00','11-11-2022T00:00:00','18-11-2022T00:00:00','1-12-2022T00:00:00']; 
$(function() {
$('#datepicker').datepicker({
  dateFormat: 'yyyy-mm-dd',
       beforeShowDay: function(date){
           var month = date.getMonth()+1;
           var year = date.getFullYear();
           var day = date.getDate();

           // Change format of date
           var newdate = day+"-"+month+'-'+year+'T00:00:00';

           // Check date in Array
           if(jQuery.inArray(newdate, highlight_dates) != -1){
                // Pass class name and tooltip text
                return [true, "highlight"];
           }
           return [true];
       }
   });
});

Thanks

Naimish Makwana

3
Naimish Makwana

Naimish Makwana

  • 140
  • 13.5k
  • 184.2k
Jan 24 2023 3:34 AM

Hello Marrius,

Please try below code.

You can change the date formate as below.

<script type='text/javascript'>
 
// An array of highlighting dates ( 'dd-mm-yyyy' )
var highlight_dates = ['8-11-2022','11-11-2022','18-11-2022','1-12-2022'];
 
$(document).ready(function(){
 
   // Initialize datepicker
   $('#datepicker').datepicker({
       beforeShowDay: function(date){
           var month = date.getMonth()+1;
           var year = date.getFullYear();
           var day = date.getDate();
 
           // Change format of date
           var newdate = day+"-"+month+'-'+year;

           // Check date in Array
           if(jQuery.inArray(newdate, highlight_dates) != -1){
                // Pass class name and tooltip text
                return [true, "highlight"];
           }
           return [true];
       }
   });
});
</script>

CSS

.highlight a{
   background: #29f274 !important;
   color: #ffffff !important;
}

Reference link for detail : 

https://makitweb.com/how-to-highlight-selected-date-in-jquery-ui-datepicker/#:~:text=Define%20beforeShowDay%20within%20datepicker(),%5D%3B%20otherwise%20return%20%5Btrue%5D%20.

Thanks

3
Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k
Jan 23 2023 6:06 PM

I think I know where the problem is. json gets data in this format

2023-01-25T00:00:00,2023-01-24T00:00:00,2023-01-26T00:00:00

and I use

var string = jQuery.datepicker.formatDate('yy-mm-dd', date);

 

But how it should look like?

3
Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k
Jan 23 2023 4:09 PM

So, the below script works but the final part is not working despite json provide data

This (unavDates.indexOf(string) == -1) suposed to highlight the dates from json but is not

<script>
    $(document).ready(function() {
        var unavDates = new Array();
        $.getJSON(`?handler=LoadDaysCMP`, (data) => {
            var listOfEvents = data;
            for (var i in listOfEvents) {
                unavDates.push(listOfEvents[i].date);// push the date to our array for checking afterwards
            }
            debugger;
        });

        $.datepicker.regional['ro'] = {
            closeText: 'Inchide', // set a close button text
            currentText: 'Astazi', // set today text
            monthNames: ['Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie', 'Iulie', 'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie'], // set month names
            monthNamesShort: ['Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Iun', 'Iul', 'Aug', 'Sep', 'Oct', 'Noi', 'Dec'], // set short month names
            dayNames: ['Duminica', 'Luni', 'Marti', 'Miercuri', 'Joi', 'Vineri', 'Sambata'], // set days names
            dayNamesShort: ['Dum', 'Lun', 'Mar', 'Mie', 'Joi', 'Vin', 'Sam'], // set short day names
            dayNamesMin: ['Du', 'Lu', 'Ma', 'Mi', 'Jo', 'Vi', 'Sa'], // set more short days names
            dateFormat: 'dd/mm/yy' // set format date
        };

        $.datepicker.setDefaults($.datepicker.regional['ro']);

        $("#datepicker").datepicker({
            firstDay: 1,
            dateFormat: "yy-mm-dd",
            beforeShowDay: checkDates,
            onSelect: function () {
            var selected = $(this).val();
            $("#dataSelect").val(selected);
            }
        });

        debugger;
        function IsWeekend(date) {
            if (date.getDay() === 0 || date.getDay() === 6) return true;
            else return false;
        };
        debugger;
        function checkDates(date) {
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            var isDisabled = (!IsWeekend(date)) && (unavDates.indexOf(string) == -1);
            return [isDisabled];
        };
        debugger;
    });

</script>

 

3
Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k
Jan 23 2023 3:06 PM

Thank you Pasang, I will try. I had this function but there is something wrong with it

 

beforeShowDay: function (date) {
                    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                    var isDisabled = (!IsWeekend(date)) && (holidayDates.indexOf(string) == -1); // used to disable if its an holiday or weekend
                    return [isDisabled];

 

3
Pasang Tamang

Pasang Tamang

  • 72
  • 26.5k
  • 194.3k
Jan 23 2023 3:02 PM

Hi,

I would suggest to use beforeShowDay option. Please check below link for more detail and example

https://www.geeksforgeeks.org/jquery-ui-datepicker-beforeshowday-option/

 

Regards,
Pasang

2
Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k
Jan 24 2023 7:06 AM

Sachin, thank you. I added

<script type="text/JavaScript" src=" https://MomentJS.com/downloads/moment.js"></script>

to my _Layout page but I have no change in script behavior

$.getJSON(`?handler=LoadDaysCMP`, (data) => {
                if (!jQuery.isEmptyObject(data)) {
                    var listOfEvents = data;
                    for (var i in listOfEvents) {
                        unavDates.push(moment(listOfEvents[i].date).utc().format('YY-MM-DD'));
                    }
                }
                
            });

 

2
Sachin Singh

Sachin Singh

  • 7
  • 55.8k
  • 82.8k
Jan 24 2023 6:33 AM

Try to use moment.js for date format


var unavDates = new Array();
        $.getJSON(`?handler=LoadDaysCMP`, (data) => {
            var listOfEvents = data;
            for (var i in listOfEvents) {
                unavDates.push(moment(listOfEvents[i].date).utc().format('YY-MM-DD'));
            }
           
        });
$("#datepicker").datepicker({
            firstDay: 1,
            dateFormat: "yy-mm-dd",
            beforeShowDay: checkDates,
            onSelect: function () {
            var selected = $(this).val();
            $("#dataSelect").val(selected);
            }
        });

        function IsWeekend(date) {
            if (date.getDay() === 0 || date.getDay() === 6) return true;
            else return false;
        };
        debugger;
        function checkDates(date) {
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            var isDisabled = (!IsWeekend(date)) && (unavDates.indexOf(string) == -1);
            return isDisabled;
        };

 

2
Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 149k
Jan 24 2023 6:11 AM

Thank you Naimish, my function works very well if array is like

var unavDates = ["2023-01-23", "2023-01-24", "2023-01-25"], I can't manage to converse date type 2023-01-25T00:00:00

Anyway, I implemented your suggestion like

beforeShowDay: function (date) {
   var year = date.getFullYear();
   var month = date.getMonth() + 1;
   var day = date.getDate();
        var newdate = year + "-" + month + '-' + day;
        if (jQuery.inArray(newdate, unavDates) != -1) {
        return [true, "highlight"];
        };
         return [true];
         },

but I have no highlight in calendar. array unavDates output is

2023-01-25T00:00:00,2023-01-24T00:00:00,2023-01-26T00:00:00

What am I doing wrong?

Thank you