2👍
Your code looks fine. I just added an empty option that reflects the initial state of the chart where no data is displayed yet. Accordingly I changed the event listener on the select element as follows:
document.getElementById('job-role').addEventListener('change', function() {
chart.data.datasets = this.value == 'none' ? [] : jobDatasets[this.value];
chart.update();
});
Please take a look at your amended code and see how it works.
const chart = new Chart('jobChart', {
type: 'line',
data: {
labels: ["1", "2", "3", "4", "5", "6", "7", "8", "9+"],
datasets: []
},
});
const jobDatasets = {
backend: [{
label: "10th Percentile",
borderColor: "#c4c1ff",
backgroundColor: "#c4c1ff",
data: [0, 10, 5, 2, 20, 30, 45, 33, 67]
}, {
label: "25th Percentile",
borderColor: "#645bff",
backgroundColor: "#645bff",
data: [5, 12, 14, 15, 19, 31, 55, 61, 62]
}],
frontend: [{
label: "10th Percentile",
borderColor: "#c4c1ff",
backgroundColor: "#c4c1ff",
data: [35, 11, 49, 45, 55, 47, 5, 62, 1]
}, {
label: "25th Percentile",
borderColor: "#645bff",
backgroundColor: "#645bff",
data: [10, 31, 48, 49, 59, 65, 67, 76, 12]
}],
fullstack: [{
label: "10th Percentile",
borderColor: "#c4c1ff",
backgroundColor: "#c4c1ff",
data: [11, 37, 10, 27, 62, 52, 8, 19, 24]
}, {
label: "25th Percentile",
borderColor: "#645bff",
backgroundColor: "#645bff",
data: [8, 25, 28, 30, 38, 45, 58, 62, 74]
}]
};
document.getElementById('job-role').addEventListener('change', function() {
chart.data.datasets = this.value == 'none' ? [] : jobDatasets[this.value];
chart.update();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<b>Chart Type</b>
<select id="job-role">
<option value="none"></option>
<option value="backend">Backend Engineer</option>
<option value="frontend">Frontend Engineer</option>
<option value="fullstack">Fullstack Engineer</option>
</select>
<div style="position: relative; width:85vw">
<canvas id="jobChart" height="110"></canvas>
</div>
Source:stackexchange.com