I transfer the data for plotting with the help of buttons, how to remake the code for transmitting it using the drop-down list? That is, the buttons are replaced by "dropdown".

Example https://plnkr.co/edit/cR0VCbeenPa1YwanWqni?p=preview

html

<canvas id="myChart" height="100"></canvas> <button id="firstData">Add first data</button> <button id="secondData">Add second data</button> <select id=" "> <option value=" ">Add first data</option> <option value=" ">Add second data</option> <option value=" ">etc</option> </select> 

scripts

 var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "Compras", backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255,99,132,1)', borderWidth: 2, data: [15, 120, 25, 48, 120, 77, 5], fill: false }], options: { legend: { display: true } } }; var ctx = $("#myChart").get(0).getContext("2d"); var myBarChart = new Chart(ctx, { type: "line", data: data, }); $('button#firstData').click(function() { var firstData = { label: "Compras", backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255,99,132,1)', borderWidth: 2, data: [15, 120, 25, 48, 120, 77, 5], fill: false }; data.datasets.push(firstData); myBarChart.update(); }); 

    1 answer 1

    If you mean to handle the change event of the drop-down list, you can handle the onchange event

    html

      <select id="dropdown"> <option value="first">Add first data</option> <option value="second">Add second data</option> <option value="etc">etc</option> </select> 

    js

     $('#dropdown').change(function(){ const val = $(this).val(); switch (val){ case 'first': var firstData = { label: "Compras", backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255,99,132,1)', borderWidth: 2, data: [15, 120, 25, 48, 120, 77, 5], fill: false }; data.datasets.push(firstData); myBarChart.update(); break; case 'second': var newDataset = { label: "Vendas", backgroundColor: 'rgba(99, 255, 132, 0.2)', borderColor: 'rgba(99, 255, 132, 1)', borderWidth: 2, data: [10, 20, 60, 40, 50, 60, 70], fill: false } data.datasets.push(newDataset); myBarChart.update(); break; } }); 

    Example: https://plnkr.co/edit/zjwan468hEgVmmyHiZKu?p=preview