Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the (this) attribute inside onSelect event of persian datepicker jquery plugin

I have multiple instances of a class inside the dom. like the example below.

let element = $(".datepicker-birthdate").pDatepicker({
    observer: true,
    altField: '.observer-example-alt',
    format: 'YYYY/MM/DD',
    initialValue: false,
    autoClose: true,
    calendar:{
        'persian': {
            'locale': 'fa',
            'showHint': false
        },
        'gregorian': {
            'locale': 'en',
            'showHint': false
        }
    },
    onSelect: function (date, e){
        e: is undefine here also
        element: is the last instance of .datepicker-birthdate
    }
});

the element always return the last instance of date picker, however i want to access the one that I have changes. Does anyone has a solution around this?

like image 777
Sarasjd Avatar asked Oct 16 '22 01:10

Sarasjd


2 Answers

In fact the library should provide the this object inside onSelect event, while they did not, perhaps using a foreach loop on the class as Rory McCrossan described would be the best alternative.

like image 85
Ala Shariaty Avatar answered Oct 18 '22 13:10

Ala Shariaty


Assuming that the onSelect function does not receive the event or the element as parameters, which seems to be the case given your description of them being undefined in the question, then you can instead manually loop through the elements in the class and instantiate the date picker on them individually. This allows you to maintain the this reference within the select handler function:

$(".datepicker-birthdate").each(function() {
  let $datePicker = $(this);
  $datePicker.pDatepicker({
    observer: true,
    altField: '.observer-example-alt',
    format: 'YYYY/MM/DD',
    initialValue: false,
    autoClose: true,
    calendar: {
      'persian': {
        'locale': 'fa',
        'showHint': false
      },
      'gregorian': {
        'locale': 'en',
        'showHint': false
      }
    },
    onSelect: function(date) {
      // use $datepicker as needed here...
      $datePicker.addClass('foo');
    }
  });
});
like image 41
Rory McCrossan Avatar answered Oct 18 '22 14:10

Rory McCrossan