1

I used this ,to multiply doughnut chart according as array(arr) has,but it can't change to object,(data has string type).So chart doesn't appear here..,how fix it

   var arr=['HTML','CSS','JS'],i,data;  
   data ='[';
   for(i=0;i<arr.length;i++){        
              if(i==arr.length-1){              
                                 data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]}';
                                 }
                             else{
                                data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]},';
                                 }
                         }
  data += ']';

 var dat = data;
window.onload = function () {
            var ctx = document.getElementById("chart-area").getContext("2d");                         
            window.myBar = new Chart(ctx).Doughnut(dat,{
                                              responsive: true,
                                                       });      
                            };

//want like this

dat =[{value:"300",color:"#fff",highlight:"#aaa",label:"HTML"},
{value:"200",color:"#fff",highlight:"#aaa",label:"CSS"}];

1 Answer 1

0

You are creating your array as a String.

You need to create an array of objects [{},{},{}].

The method used to INSERT a new object in an array is PUSH().

Check the fiddle. Now it´s working OK (move the mouse on the screen to see the chart is there (you will only see it when mouse is over it):

window.onload = function() {

  var arr = ['HTML', 'CSS', 'JS'],
    i, data;
  data = [];
  for (i = 0; i < arr.length; i++) {
    if (i == arr.length - 1) {
      data.push({
        value: "300",
        color: "#fff",
        highlight: "#aaa",
        label: arr[i]
      });

    } else {
      data.push({
        value: "300",
        color: "#fff",
        highlight: "#aaa",
        label: arr[i]
      });

    }
  }

  var dat = data;

  var ctx = document.getElementById("chart-area").getContext("2d");
  window.myBar = new Chart(ctx).Doughnut(dat, {
    responsive: true,
  });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/nnnick/Chart.js/master/Chart.js"></script>

<canvas id="chart-area"></canvas>

2
  • Thank you ----------------@Alejandro Teixeira Munoz Jun 17, 2015 at 3:25
  • You welcome, plz, mark question as solved if this is the solution!! thnks! Jun 17, 2015 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.