Razmi
Razmi

Reputation: 209

Changing an object value using onChange event

I am trying to change a chart data using the id given in a select box, for that I used an onChange event:

<label for="patientId">Choose a patient:</label>
 <select name="patient" id="patient" onchange="myFunction(this.value)">
  {% for item in patientId %}
   <option value="{{item}}">
    {{item}}
   </option>
  {% endfor %}
 </select>

<canvas id="weeklyChart"></canvas>

The chart data is a bug object that looks like that:

var myLineChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: {{ hourArray|safe}},
    datasets: [{
      label: "Value",
      lineTension: 0.3,
      backgroundColor: "rgba(78, 115, 223, 0.05)",
      borderColor: "rgba(78, 115, 223, 1)",
      pointRadius: 3,
      pointBackgroundColor: "rgba(78, 115, 223, 1)",
      pointBorderColor: "rgba(78, 115, 223, 1)",
      pointHoverRadius: 3,
      pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
      pointHoverBorderColor: "rgba(78, 115, 223, 1)",
      pointHitRadius: 10,
      pointBorderWidth: 2,
      data: {{ glucoseArray|safe}},
    }],
  },
}

In the onChange function I have the following logic:

function myFunction(val) {
  let hourArray = [];
  let glucoseArray = [];
  for (let i = 0; i < deviceList.length; i++) {
    if (deviceList[i].patientId == val) {
      hourArray.push(deviceList[i].hour);
      glucoseArray.push(deviceList[i].glucoseValue);
    }
  }
  myLineChart.data.datasets[0].data = glucoseArray;
  myLineChart.data.labels = hourArray;
  console.log(myLineChart.data.datasets[0].data);
  console.log(myLineChart.data.labels);
}

In the console.log() I have exactly the data I need, but nothing happens on the page. What can I do, so my function will render the right data for the chart.

Upvotes: 2

Views: 1267

Answers (1)

TrebuAB
TrebuAB

Reputation: 131

You have to update the data you add. For that use myLineChart.update()

For change data without animation you can use none as mode

Upvotes: 2

Related Questions