[Chartjs]-How to select and pass array object to data setting of chart.js config?

3πŸ‘

βœ…

The value of your hidden input is a string.

You are creating an array with a single element containing that string.

You need to split the string first, delimiting by the , character.

Trimming whitespace is also helpful too.

See below.

<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<body>
    <canvas height="100px" id="myChart"></canvas>
    <input type="hidden" id="0" value="10, 12">
    <script>
        obj = document.getElementById('0').value.replace(" ", "").split(',')
        console.log(obj);
        const labels = ['Type 1', 'Type 2'];
        const data = {
            labels: labels,
            datasets: [
                {
                    backgroundColor: 'rgb(0, 255, 0)',
                    data: obj,
                    barThickness: 50
                }]
        };
        const config = {
            type: 'bar',
            data: data
        };
        const myChart = new Chart(
            document.getElementById('myChart'),
            config
        );
    </script>
</body>

2πŸ‘

The line obj = [document.getElementById('0').value]; will result in an array with the string "10, 12" as value. To convert the string to an array try split method: obj = document.getElementById('0').value.split(",");.

Now you have an array with the string values "10" and " 12". Not sure if chat.js can handle this, if not you can use the map funtion to iterate over the vales and covert the to numbers

Leave a comment