How to visualize data with chart.js properly?

👍:0

Your button has type="submit". This submits the form when you click it effectively refreshing it. Change it to type="button"

<input type="button" id="btnSubmit" value="Submit" />

The data property for a dataset should be an array. So you can take out the outer loop and directly plug in newArray

var ctx = $("#myChart").get(0).getContext("2d");
var data = {
    labels: [1, 5, 8, 4, 5, 6, 7, 8, 9, 10],
    datasets: [
        {
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#fff",
            data: newArray
        }
    ]
}

With these 2 changes, putting in a first and last value (say 20 and 60) will plot your chart.

However, IF you want the data to align with the original indices (and not be pushed to the left), you should be inserting null values in your first loop

if (array[i] >= firstVal && array[i] <= lastVal) {
    newArray.push(array[i]); // Add to new array
}
else {
    newArray.push(null);
}

Leave a comment