I'm working with Charts and I need to show some results on a pie chart. This the pure Chart Javascript code
var ctxP = document.getElementById("pieChart").getContext('2d');
var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: ["Red", "Green", "Yellow", "Grey", "Dark Grey"],
datasets: [
{
data: [600, 50, 100, 40, 120],
backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360"],
hoverBackgroundColor: ["#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774"]
}
]
},
options: {
responsive: true
}
});
In my HTML I have the following code, which fills me with an input hidden by each "brand" that I bring from the backend
<div class="col-12 my-5 d-flex justify-content-center">
<input th:each="b : ${brands}" type="hidden" th:value="${b.name}" class="brands">
<canvas id="pieChart" style="max-width: 40%;"></canvas>
</div>
Then when rendering that code and when inspecting the code of the page you can see (in this case) the following.
<input type="hidden" value="Intels" class="brands">
<input type="hidden" value="AMD" class="brands">
<input type="hidden" value="Western Digital" class="brands">
<input type="hidden" value="Intel" class="brands">
<input type="hidden" value="GeForce" class="brands">
<input type="hidden" value="Example" class="brands">
<input type="hidden" value="ExampleBrand" class="brands">
The problem is that, with my little experience with Javascript, I have not been able to pass each name (value) of my brands elements to Javascript in order to display them in the pie chart. I have tried the following but I get some errors which I put as comments.
var b = document.getElementsByClassName("brands");
var brands = [];
for (brand in b) {
brands.push(b);
}
console.log(brands.length); //ME DEVUELVE 10 Y NO 7.
for (brand in brands) {
console.log(brand.value); // ME DEVUELVE UNDEFINED 10 VECES.
}
So what I need is to obtain each element with the class "brands" and the value of each one to save it in this line of the Chart so that instead of leaving colors I get my "brands". Best regards.
labels: ["Red", "Green", "Yellow", "Grey", "Dark Grey"]