Why does this not work? (setting min date on date picker)

I’m running the following code to initialize the date picker on all date input fields. (ver 4)

$('.datepicker').mobiscroll().calendar({
   display:'bottom',
   dateFormat: js_dateformat,
   buttons:['clear'],
   setOnDayTap:true,
   min: $(this).data('mindate'),
   responsive: {
       small:{
         display: 'center'
       }
   },
   onClear: function(event,inst){
     inst.hide();
   }
});

For the most part this works great, except in some date fields I want to prevent the selection of dates prior to a certain day. So I understand that I can use the “min” attribute but I don’t want to have to call this initialization separately for each field with different parameters because I have hundreds of date fields so I’m trying to minimize my code. So I’m setting the minimum date on a data attribute in the element, and then I’m expecting to be able to grab that value in the mobiscroll initialization code above.

min: $(this).data('mindate')

Unfortunately this does not seem to work. $(this).data(‘mindate’) evaluates to a date string like ‘2021-05-06’. So why does this not work?

Well, my understanding was that $(’.datepicker’).mobiscroll().calendar({}) was effectively looping through all the elements with the class datepicker. I don’t know how jQuery does it internally but I found another way to accomplish what I want.

First I do the loop, grab the data values, and then initialize the datepicker each time within the loop.

  $('.datepicker').each(function(i, obj){
    var mindate = $(this).data('mindate');
    var maxdate = $(this).data('maxdate');

    $(this).mobiscroll().calendar({
       display:'bottom',
       dateFormat: js_dateformat,
       buttons:['clear'],
       setOnDayTap:true,
       min: mindate,
       max: maxdate,
       responsive: {
           small:{
             display: 'center'
           }
       },
       onClear: function(event,inst){
         inst.hide();
       }
    });
  });

Seems to work, but I’m guessing this is less efficient. If there’s a better way to accomplish what I want I’d love to hear about it.

Hi @Vincent_Wansink

This is actually how the “this” works (pun not intended :slight_smile: ). In short: what matters is how the this is called. In you first question this is used inside an object literal, in your second inside a function. A very good and descriptive explanation can be found in this answer on stackoverflow.

Also if you are looking for minimizing the code, you can always make it your own extension to jquery. Something like:

$('datepicker').MyCalendar();
1 Like