Chartjs-Javascript and Chart.js not taking user input assuming it is a variable scope issue

0๐Ÿ‘

โœ…

I assume you call calculate when the user has given input and you create the chart outside of any function. This would mean you create the chart immediately when loading the script, when the user has not given any input yet. you want to create the chart inside calculate or if you want to see the canvas before user input, you can update the chart.

Here is an example:

function handleInput() {
    let text = document.getElementById("uInput");
    var num = Number(text.value);
    if (isNaN(num)) {
        alert("bad input!");
        return;
    }
  
    var percentages = {
        perfifty: (50 / 100) * num,
        perthirty: (30 / 100) * num,
        pertwenty: (20 / 100) * num
    };
    
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ['Red', 'Blue', 'Yellow'],
            datasets: [{
                label: '',
                data: [percentages.perfifty, percentages.perthirty, percentages.pertwenty],
                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)',
                    'rgba(255, 159, 64, 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)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script>
<label for="uInput">Input:</label>
<input type="text" id="uInput">
<button onclick="handleInput()"> Submit </button>

<canvas id="myChart"></canvas>

Leave a comment