I want to make the total bars 12 when i input 12. how to make the length of variable labels same like my input???
this is my code:
function updateChart() {
let val = $("#num-input").val()
let valNum = parseInt(val)
console.log(valNum)
let labels = []; // this length = bar total
labels = $("#num-input").val()
console.log(labels)
const data = {
labels: labels,
datasets: [{
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [10, 20, 5, 2, 20, 30, 45], // = value for each bar
}]
};
const config = {
type: 'bar',
data: data,
options: {}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
}
this is my result
This is because chart.js expects an array so you will need to make an array containing 12 labels first instead of passing the number 12 to the labels array:
function updateChart() {
let val = $("#num-input").val()
let valNum = parseInt(val)
console.log(valNum)
let labels = []; // this length = bar total
for (let i = 0; i < $("#num-input").val(); i++) {
labels.push(i) // or any other value you want your label to have
}
const data = {
labels: labels,
datasets: [{
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [10, 20, 5, 2, 20, 30, 45], // = value for each bar
}]
};
const config = {
type: 'bar',
data: data,
options: {}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
}