I want to add & delete datasets from chart.js using checkboxes.
Right now I am adding using this:
var ds1 = {
label: ..
data: .. etc
};
data.datasets.push(ds1);
When I uncheck any of the checkboxes, it's always deleting the last dataset added, which is not necessary the one of the checkbox.
I'm using data.datasets.pop(ds1);
to remove the when a checkbox is clicked.
js convention is to call it ctx . An object literal containing the data and the configuration options that Chart. js will use to build your chart. The required properties are type and data . In our example type is 'line' because we want a line chart.
destroy() Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart. js, along with any associated event listeners attached by Chart.
If you're removing using data.datasets.pop(ds1)
you'll never get the result you're looking for. The dataset
property is an array, so let's just focus on arrays and ignore Chart.js.
First issue is that the pop()
method of the Arrays type does not take an argument, so providing which element you want to remove is irrelevant. Pop()
will always remove the last element from an array.
To remove a specific element from the array you need to use the splice()
function.
Let's say that ds1
is the element you want to remove.
let removalIndex = data.datasets.indexOf(ds1); //Locate index of ds1
if(removalIndex >= 0) { //make sure this element exists in the array
data.datasets.splice(removalIndex, 1);
}
This will delete the 1 record in the array starting at the index we located ds1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With