I have a chart that gets the data values from a table column. It currently works on its own, but I want to add a functionality that changes/updates the data of the chart on button click. I tried this code but it doesn't work (arrays are very confusing for me):
var canvasP = document.getElementById("pieChart");
var table = document.getElementById("myTable");
var nameArr = [];
var data1Arr = [];
var data2Arr = [];
var tableLen = table.rows.length;
var i;
for (i = 1; i < tableLen; i++) {
nameArr.push(table.rows[i].cells[0].textContent);
data1Arr.push(table.rows[i].cells[1].innerHTML);
data2Arr.push(table.rows[i].cells[2].innerHTML);
}
nameArr.pop();
data1Arr.pop();
data2Arr.pop();
var ctxP = canvasP.getContext("2d");
var myPieChart = new Chart(ctxP, {
type: "pie",
data: {
labels: nameArr,
datasets: [{
data: data1Arr,
backgroundColor: ["#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1", "#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1"],
label: "Data"
}]
},
options: {
legend: {
display: true,
position: "right"
},
title: {
display: true,
text: "Data 1"
}
}
});
// the button functions below do not work. I am trying to load the array variables into the data:
document.getElementById("btn1").addEventListener("click", function() {
myPieChart.data.datasets.data = data1Arr;
});
document.getElementById("btn2").addEventListener("click", function() {
myPieChart.data.datasets.data = data2Arr;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<table id='myTable'>
<thead>
<tr>
<th>Name</th>
<th>1st data</th>
<th>2nd data</th>
</tr>
</thead>
<tbody>
<tr>
<th>Item 1</th>
<td>337</td>
<td>411</td>
</tr>
<tr>
<th>Item 2</th>
<td>290</td>
<td>110</td>
</tr>
<tr>
<th>Item 3</th>
<td>197</td>
<td>800</td>
</tr>
<tr>
<th>Item 4</th>
<td>765</td>
<td>211</td>
</tr>
<tr>
<th>Item 5</th>
<td>331</td>
<td>451</td>
</tr>
<tr>
<th>Item 6</th>
<td>957</td>
<td>871</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total</th>
<td id='curPop'>2877</td>
<td>2854</td>
</tr>
</tfoot>
</table>
<canvas id='pieChart'></canvas>
<button id="btn1">
Data 1
</button>
<button id="btn2">
Data 2
</button>
What I would want is that when the Data 2 button is clicked, it loads the appropriate data from the table (2nd data) into the pie chart, and that the Data 1 button loads the 1st data of the table.