Murcielago
Murcielago

Reputation: 1005

chart.js label with if statement

for traduction purposes, I am trying to set up my chart.js labels based on html tag text. Being a beginner to javascript, this a bit of a challenge.

Here is what I am trying to do:

html code:

<div class="col-lg-6">
  <div id='tag4' class="card-footer small text-muted">{% trans 'ITEMS IN DIFFICULTY' %}</div>
  <div class="bar-chart block">
    <canvas id="myChart3" height="175"></canvas>
  </div>

and my chart.js code:

var myChart3 = new Chart(ctx3, {
  type: 'bar',
  data: {
    labels: labels3,
    datasets: [{
      label: if (document.getElementById('tag4').value == 'ITEMS IN DIFFICULTY') {
        'low performing items (quantity sold/week)'
      }
      else {
        'references en difficulté (quantité vendu/semaine)'
      },
      data: defaultData3,
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
      ],
      borderWidth: 1
    }],
    options: {
      scales: {
        yAxes: [{
          gridLines: {
            drawOnChartArea: false,
            ticks: {
              beginAtZero: true
            }
          }
        }],
      }
    }
  }
})

the result is that the graph does not show up. I am not sure if the issue is because there is something wrong with my if statement or if its not something that can be done with chart.js labels. Any help is more than welcomed!

Upvotes: 1

Views: 1584

Answers (1)

Antoni Silvestrovič
Antoni Silvestrovič

Reputation: 1035

What you need is a ternary operator, it works like this:

let isTrue = true
let a = isTrue ? 1 : 0

if isTrue is true, then a is 1, if false, a is 0

In your case, you can pass following as a label:

document.getElementById('tag4').textContent == 'ITEMS IN DIFFICULTY' ? 'label if true' : 'label if false'

Upvotes: 1

Related Questions