0

i am using chart.js i want to dynamically update label of my bar chart i have an array in javascript that takes it values from ajax now the issue is i want to pass each element of array in the label

   labels: [array[0],array[1],array[2],array[3],array[4]],

this is what am i doing i m hard-coding each element of array but this is not what i wanted i want to display each element of array dynamically. I was thinking to take the length of array and then loop through the array till its length but again the issue is labels prop. of chart.js doesn't allow me to write JavaScript code in it....kindly help me

this is my code

         var label_values=$('.labels').text();
         //label_values has this string 
           "09:00:0010:00:0011:00:0012:00:0013:00:00"
         var array=[];
         array = label_values.match(/(\d+:){2}\d\d/g);
         var canavas=jQuery('<canvas id="myChart" style="width: 75%; display: block; border: 0px; height: 0px; margin: 0px; position: absolute; left: 0px; right: 0px; top: 70px; bottom: 0px";></canvas>');
         canavas.appendTo(overlay_body);
         var ctx = document.getElementById("myChart");
       var myChart = new Chart(ctx, {
       type: 'horizontalBar',
        data: {
    labels: [array[0],array[1],array[2],array[3],array[4]],
    datasets: [{
        label: 'Hourly Attendance',
        data: [12, 19, 3, 5, 2],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)'
        ],
        borderWidth: 1
    }]
},
options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true
            }
        }],
        xAxes: [{
            ticks: {
                max:60,
                min:0,
                step:10,
                beginAtZero:true
            }
        }],


       }
   }
  });
      }// end 2nd ajx
    });
      }
    });
iqra
  • 115
  • 1
  • 12

1 Answers1

0

labels property accepts array so you can just pass the whole array

labels: array
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40