Mike Harrison
Mike Harrison

Reputation: 776

Showing array of events with FullCalendar

I have the following script using FullCalendar:

  var calendarEl = document.getElementById('calendar');

  var bookingsEl = document.getElementById('bookings');

  var bookings = bookingsEl.innerText;
  var bookings = "["+bookings+"]"

  console.log(bookings);

  if(calendarEl) {

    var calendar = new Calendar(calendarEl, {
      plugins: [ dayGridPlugin ],
      firstDay: 1,
      height: 'auto',
      events: bookings,
      header: {
        left:   'prev',
        center: 'title',
        right:  'next'
      }
    });

  calendar.render();

}

The console.log for bookings looks like this:

[{start:"2020-08-12",end:"2020-08-25",rendering:"background"},{start:"2020-09-11",end:"2020-09-30",rendering:"background"},{start:"2020-08-26",end:"2020-08-28",rendering:"background"}]

If I copy and paste this for the events setting it works fine, but as it is I am getting no events showing in the calendar.

I am at a loss what to do next to get this to work! Any help greatly appreciated.

Upvotes: 0

Views: 466

Answers (1)

nibnut
nibnut

Reputation: 3127

Right, so the issue is that the "events" attribute expects a javascript array, and you are passing it a string value that looks like a stringyfied array when you look at the console output.

So you need to convert your string into a Javascript array of objects; from what you've shown, "bookingsEl.innerText" contains a list of objects in string form. So I would try this:

var bookings = JSON.parse("["+bookings+"]");

This will parse a JSON array into it's javascript equivalent object. NOTE: your JSON string is not standardized: the object attributes need to be quoted too, i.e. {"start":"2020-08-12","end":"2020-08-25","rendering":"background"}

BONUS An array and the string representation of an array look different in the javascript console. As a test, try this:

var bookings = JSON.parse("["+bookings+"]");
console.log("This is a javascript array", bookings);
console.log("This is a string representation of an array", "[" + bookingsEl.innerText + "]");

You should see they look quite different in the console... enter image description here

Upvotes: 1

Related Questions