javascriptpikaday

How do I use Pikaday calendar with unique Div's


I have Div's with the same class name. I can loop through them and console out their unique IDs that have been assigned. I also have code for pikaday that works fine with one Div. I'm now trying to loop through the Div's and assign a pikaday calendar to each one but my code tha worked for one Div isn't working for the multiple divs. I just cannot figure out why. Thank you for any help.

$('.main_records').each(function() {
  var picker = new Pikaday({
    field: this,
    numberOfMonths: 2,
    mainCalendar: 'right',
    onSelect: date => {
    var formatDate = moment(date).format('MM/DD/YYYY');
    console.log(formatDate);
    document.getElementsByClass('.main_records').innerHTML = formatDate;
  });
});

If I remove this code:

    numberOfMonths: 2,
    mainCalendar: 'right',
    onSelect: date => {
    var formatDate = moment(date).format('MM/DD/YYYY');
    console.log(formatDate);
    document.getElementsByClass('.main_records').innerHTML = formatDate;

pikaday pops up but then I can't assign the selected date to my Div element.


Solution

  • So document.getElementsByClass is not a valid method, you'd need to use: document.getElementsByClassName, but that returns a NodeList, not a single element - however you're already using jQuery so we can change the code.

    $('.main_records').each(function() {
      var currentElement = $(this); // Store reference to current element
      var picker = new Pikaday({
        field: this,
        numberOfMonths: 2,
        mainCalendar: 'right',
        onSelect: function(date) {
          var formatDate = moment(date).format('MM/DD/YYYY');
          console.log(formatDate);
          currentElement.html(formatDate); // Set the innerHTML of the current element
        }
      });
    });