Integrating Chart.js in Qualtrics | XM Community
Skip to main content

Dear community,

The following script from https://www.chartjs.org/docs/latest/getting-started/ does not seem to be working in my survey. I am very new to Java and HTML and was hoping you could you help me figure out why it's not working. Thank you very much for your help!

In the question itself, I have included the following code in HTML:

<div><canvas id="myChart"></canvas></div>

 

I have added the following code the the header in HTML:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

 

To the question JSS, I have included the following code:
  const ctx = document.getElementById('myChart');

  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: 'Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
      datasets: {
        label: '# of Votes',
        data: <12, 19, 3, 5, 2, 3],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
 

I think there’s an issue with rendering using the canvas element. I would recommend using a library that supports the more general div. 

Something like HighCharts or Plotly. IMHO Plotly would be better, as you could learn it once and use it in R/Python also.

A couple of things to note:

  1. Do not add a <script> element inside you question HTML. Qualtrics often strips it out.
  2. You need to add your chart config in the question JS.
  3. Most charting libraries will ask you to create a blank element <div id="myChart”></div>. If you have only this in your question HTML, it will be removed by Qualtrics. To avoid this, make sure you have something else in the question html also. Like &nbsp;<div id="myChart”></div> or <div id="myChart"></div><div>Something about the Chart</div>

 

Here’s an example:

Question HTML:

<div id="myChart"></div><div>Something about the Chart</div>

Question JS:

Qualtrics.SurveyEngine.addOnReady(function () {
jQuery.getScript("https://cdn.plot.ly/plotly-2.29.1.min.js").done(createChart);
});

function createChart() {
const chartConfig = h
{
x: {"giraffes", "orangutans", "monkeys"],
y: ,20, 14, 23],
type: "bar"
}
];

Plotly.newPlot("myChart", chartConfig);
}

Just make changes to the createChart function as per your needs.


Leave a Reply