How to update Chart.js according to the option selected from my drop-down list?
I am trying to update my chart based on the option selected from my drop down list.
This is my JSON response:
{
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
{
"id": 6,
"name": "Jose",
"orders_by_user": 1,
"rol": 2
},
{
"id": 7,
"name": "Miguel",
"orders_by_user": 1,
"rol": 2
}
]
}
Through ajax I obtain the data to make the graph and upload options to my drop-down list. A little snippet of code:
success: function (response) {
console.log(response);
var order = [];
var user = [];
for (var i in response.orders) {
order.push(response.orders[i].orders_by_user);
user.push(response.orders[i].name);
$("#operator").append('<option value='+response.orders[i].id+'>'+response.orders[i].name+'</option>');
}
renderChart(order, user);
My Select:
<select class="form-control" name="operator" id="operator" >
<option>All</option>
</select>
With this I get the selected text from my drop-down list.
var selectOption = $('#operator');
selectOption.on('change', function() {
var option = $("option:selected", selectOption).text();
So if the selected option is "Luis", the graph would have to be updated graphing with the information that corresponds to "Luis" (see JSON response)
This is how I try to update my chart:
function renderChart(order, user) {
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
//code...
});
//my select
var selectOption = $('#operator');
selectOption.on('change', function() {
var option = $("option:selected", selectOption).text();
myChart.data.labels = option;
if (option == 'All') {
myChart.data.labels = user,
myChart.data.datasets[0].data = order;
} else {
myChart.data.labels = option;
myChart.data.datasets[0].data = order;
}
myChart.update();
});
}
I think my problem is here:
} else {
myChart.data.labels = option;
myChart.data.datasets[0].data = order;
}
The logic is if option is not equal to 'All', then myChart.data.labels = "Luis"; and myChart.data.datasets [0] .data = "2";
How can I go back through my user and order array? Exactly in user are all the names of the operators and in order are the quantities of completed orders that correspond.
Could you please guide me to solve this problem?
Please or to participate in this conversation.