I have a hidden input
<input type="hidden" id="0" value="10, 12">
and I am using
obj = [document.getElementById('0').value];
in a script tag to retrieve and use the value of the hidden input as the data array in the setting of Chart.js
const data = {
labels: labels,
datasets: [
{
backgroundColor: 'rgb(0, 255, 0)',
data: obj,
barThickness: 50
}]
};
I have read Chart.js unable to display data and Treat getElementById return value as array but both those questions answers suggest converting the object to an array which I have done and it still doesn’t work.
Not able to pass array of data to chart.js in React Was a react problem and I tried adapting it but it didn’t work either.
The desired output I want can be seen in this code snippet here:
<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<body>
<canvas height="100px" id="myChart"></canvas>
<input type="hidden" id="0" value="10, 12">
<script>
obj = [document.getElementById('0').value];
console.log(Array.isArray(obj), obj);
const labels = ['Type 1', 'Type 2'];
const data = {
labels: labels,
datasets: [
{
backgroundColor: 'rgb(0, 255, 0)',
data: [10,12],
barThickness: 50
}]
};
const config = {
type: 'bar',
data: data
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
</body>
How can I achieve the same solution by somehow selecting the hidden input and passing that array as the data?
I have used console.log();
to confirm that the object is an array and that it has the correct value.
Attempts:
- I’ve tried surrounding the object with [] like so
data: [obj],
but then nothing gets displayed (probably because it’s already an array?) - I’ve tried converting the array to a list as suggested here: Turn Array Into List With JavaScript but still nothing gets displayed.
- I’ve tried changing the values of the hidden input to be
value="'10', '12'"
but still nothing gets displayed.