My query involves JavaScript. I have an HTML template with a button (b1) that, when clicked, assigns an array to a variable called tempdata. The issue arises when trying to display this tempdata array using alert() outside the onclick function; nothing happens. However, if I try the alert inside the onclick function, it works as expected. My requirement is to use the tempdata array outside the onclick function in order to pass it to the data tag for the config variable.
So, my question is: How can I set the tempdata array and successfully pass it to the data tag?
var cusomernames=[];
var myObj = [{
"region":"APAC",
"customers": [
{ "name":"A", "count":100 },
{ "name":"B", "count":35 },
{ "name":"C", "count":90 }
]
},
{
"region":"ASEAN",
"customers": [
{ "name":"A", "count":30 },
{ "name":"B", "count":35 },
{ "name":"C", "count":90 }
]
}
];
function myFunction() {
var datasum=[];
for(var i = 0; i < myObj.length; i++) {
if(myObj[i].region == "APAC"){
for(var p=0;p<3;p++){
datasum.push(myObj[i].customers[p].count);
cusomernames.push(myObj[i].customers[p].name);
}
}
}
return datasum;
}
window.onload = function() {
var b1=document.getElementById('b1');
var tempData=[];
b1.onclick=function(){
tempData=myFunction();
alert(tempData);
}
var config = {
type: 'funnel',
data: {
datasets: [{
data: tempData,
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}],
labels: ["A","B","C"]
},
options: {
responsive: true,
sort: 'desc',
legend: {
position: 'top'
},
title: {
display: true,
text: 'Chart.js Funnel Chart'
},
animation: {
animateScale: true,
animateRotate: true
}
}
};
var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx, config);
};