I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Here is the code snippet:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>


<body>
    <div id="header">
        <h1>School Project</h1>
    </div>

    <nav>
        <a href="#" onclick="showChartsPage()">Charts</a>
        <a href="#" onclick="showFormsPage()">Send Forms</a>
    </nav>

    <div id="chartsPage">
        <h2>Chart Display Page</h2>
    </div>

    <form id="dataForm">

        <div>
            <label for="labelsInput">Labels (comma-separated):</label>
            <input type="text" id="labelsInput" placeholder="Label 1, Label 2, Label 3">
        </div>

        <label for="dataInput">Enter Data: </label>
        <input type="text" id="dataInput" required>

        <label for="chartType">Select Chart Type you want:</label>
        <select id="chartType">
            <option value="bar">Bar Chart</option>
            <option value="pie">Pie Chart</option>
            <option value="radar">Radar Chart</option>
            <option value="line">Line Chart</option>
        </select>

        <button onclick="generateChart()">Generate the selected chart</button>
        <div><canvas id="myChart"></canvas></div>
    </form>

    <div id="formsPage" class="card" style="display: none;">
        <h2>Send Google Forms</h2>
        <img src="Project/download.png" alt="Picture of a Form">
        <p>Send Created Google Forms here</p>
        <button onclick="sendGoogleForm()">Send Google Form</button>
    </div>


    <script>
        function showChartsPage() {
            document.getElementById('chartsPage').style.display = 'block';
            document.getElementById('formsPage').style.display = 'none';
        }

        function showFormsPage() {
            document.getElementById('chartsPage').style.display = 'none';
            document.getElementById('formsPage').style.display = 'block';
        }

        function generateChart() {
            const dataInput = document.getElementById("dataInput").value;
            const labelsInput = document.getElementById('labelsInput').value;
            const dataArray = dataInput.split(",").map(Number);
            const chartType = document.getElementById('chartType').value;

            const labels = labelsInput.split(',').map(label => label.trim());
            const data = dataInput.split(',').map(value => parseFloat(value.trim()));

            const ctx = document.getElementById('myChart').getContext('2d');

            if (window.myChart) {
                window.myChart.destroy();
            }

            window.myChart = new Chart(ctx, {
                type: chartType,
                data: {
                    labels: Array.from({
                        length: dataArray.length
                    }, (_, i) => i + 1),
                    datasets: [{
                        label: 'User Data',
                        data: dataArray,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
            });
        }

        function generateChart() {
            const chartType = document.getElementById('chartType').value;
            const userData = document.getElementById('userData').value.split(',').map(Number);

            // Use Chart.js to create a chart
            const ctx = document.getElementById('myChart').getContext('2d');
            const myChart = new Chart(ctx, {
                type: chartType,
                data: {
                    labels: Array.from({
                        length: userData.length
                    }, (_, i) => i + 1),
                    datasets: [{
                        label: 'User Data',
                        data: userData,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
    </script>
</body>

</html>

The above is the code segment that I have been working on lately.

Upon troubleshooting, I confirmed that Chart.js was properly installed. Multiple attempts with different scripts led to the same outcome where instead of displaying the desired chart, the area remained blank.

Answer №1

It appears that your script contains two functions named generateChart(), both attempting to create a chart. The second one seems to be overriding the first, potentially causing the problem.

Below is an updated version of your script with the duplicate function removed:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

<body>
    <div id="header">
        <h1>School Project</h1>
    </div>

    <nav>
        <a href="#" onclick="showChartsPage()">Charts</a>
        <a href="#" onclick="showFormsPage()"">Send Forms</a>
    </nav>

    <div id="chartsPage">
        <h2>Chart Display Page</h2>
    </div>

    <form id="dataForm">
        <div>
            <label for="labelsInput">Labels (comma-separated):</label>
            <input type="text" id="labelsInput" placeholder="Label 1, Label 2, Label 3">
        </div>

        <label for="dataInput">Enter Data: </label>
        <input type="text" id="dataInput" required>

        <label for="chartType">Select Chart Type you want:</label>
        <select id="chartType">
            <option value="bar">Bar Chart</option>
            <option value="pie">Pie Chart</option>
            <option value="radar">Radar Chart</option>
            <option value="line">Line Chart</option>
        </select>

        <button onclick="generateChart()">Generate the selected chart</button>
        <div><canvas id="myChart"></canvas></div>
    </form>

    <div id="formsPage" class="card" style="display: none;">
        <h2>Send Google Forms</h2>
        <img src="Project/download.png" alt="Picture of a Form">
        <p>Send Created Google Forms here</p>
        <button onclick="sendGoogleForm()">Send Google Form</button>
    </div>

    <script>
        function showChartsPage() {
            document.getElementById('chartsPage').style.display = 'block';
            document.getElementById('formsPage').style.display = 'none';
        }

        function showFormsPage() {
            document.getElementById('chartsPage').style.display = 'none';
            document.getElementById('formsPage').style.display = 'block';
        }

        function generateChart() {
            const dataInput = document.getElementById("dataInput").value;
            const labelsInput = document.getElementById('labelsInput').value;
            const dataArray = dataInput.split(",").map(Number);
            const chartType = document.getElementById('chartType').value;

            const labels = labelsInput.split(',').map(label => label.trim());
            const data = dataInput.split(',').map(value => parseFloat(value.trim()));

            const ctx = document.getElementById('myChart').getContext('2d');

            if (window.myChart) {
                window.myChart.destroy();
            }

            window.myChart = new Chart(ctx, {
                type: chartType,
                data: {
                    labels: Array.from({
                        length: dataArray.length
                    }, (_, i) => i + 1),
                    datasets: [{
                        label: 'User Data',
                        data: dataArray,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
            });
        }
    </script>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in Express application due to uncaught SyntaxError

I am attempting to live stream data using websockets to Chartjs, however I keep encountering the following error. main.js:1 Uncaught SyntaxError: Unexpected token < What could be causing this issue? The code for my server and HTML is as follows: ...

I am having trouble getting ng-change to work. Can someone explain how to properly implement ng

I am facing an issue where the ng-change function is not working for obtaining the team_id and team name. Can someone suggest a more efficient solution to resolve this problem? <th style="width:20%"> <select style="height: 40px; fon ...

Web Audio API functions are encountering a playback issue on iOS 13.3, despite working smoothly on previous iOS versions

I have been developing an audio visualizer using the web audio API. It was functioning smoothly on PC, however, after upgrading to iOS 13.3, it no longer operates on Apple mobile devices. The root cause of this issue remains a mystery to me. The problem s ...

maintaining the alignment of three div elements

I am struggling to keep three divs side by side within a container, each containing an image and text below it. I had this layout working perfectly before, but now the right div falls underneath the other two when the screen size is reduced, followed by th ...

The current context does not have a reference to TextBox

I am encountering an issue with my simple aspx page. Despite not using Master Content Page, I am seeing the following error: The name 'txtFirstName' does not exist in the current context Here is my Markup: <%@ Page Language="C#" %> &l ...

Empty canvas when Material UI Modal transitions states

I've been struggling to make a simple modal using material UI, but every time I try to change the state, it just shows a blank white page. Can anyone help me figure out why this is happening? Here's the code snippet: import {Button,Modal} fro ...

Using React Quill JS and looking to log to the console when a change handler is triggered?

As I dive into the world of web development, I am currently working on crafting a blog dashboard. For the text editor, I've opted to use React Quill. While following the documentation, I came across a tutorial that includes an 'on change' ha ...

Encountering errors while trying to install the npm package.json

For instance, I encountered an issue when trying to create a react project via npm. The error message indicated that it couldn't find my package.json file. Any assistance on resolving this would be highly appreciated. I will also share the process of ...

Using PHP to automatically suggest options when selecting elements from a MySQL table

My project involves creating a basic application for sending confirmation emails. I have a MySQL table that includes 4 columns: id, user_email, user_name, and user_track. The form on the app has a selectbox displaying all the stored user_email entries an ...

The absence of associative arrays in package.json

Is there a way to include an array of languages in my package.json file? I attempted the following: "langs": { "en", "es" } However, it appears to be invalid. Any suggestions on how I can properly store an array of languages in my package.json file? ...

The variable referencing an unidentified function has not been defined

I've created an anonymous function assigned to a variable in order to reduce the use of global variables. This function contains nested functions for preloading and resizing images, as well as navigation (next and previous). However, when I try to run ...

Ways to showcase numerous products within a single category label

views.py : def get_meals(request): template = loader.get_template('café/meals.html') meal_data = MealInfo.objects.all() category_data = MealsCategory.objects.all() context = { 'meals': meal_data, ' ...

Iterate through each element in the array and manipulate the corresponding data

I am trying to figure out a way to assign a unique id to each item in an array and send it to the "script.js" file for individual data processing. <script href="script.js"></sciprt> script.js: $(function(){ $('#box' ...

HTML4 section tag failing to generate columns in proper alignment

Currently, I am organizing a list of movies by decade using the article and section elements. An issue has arisen: the alignment between the second and third rows is perfect while the first row seems slightly off-kilter. Below is the code snippet in questi ...

Working with repeated fields in Google protobuf in JavaScript

Consider this scenario: you have a google protobuf message called Customer with a repeated field as shown below. message Customer { repeated int32 items = 1; } What is the procedure for setting the repeated items field in javascript? ...

Python download is not supported by Windows-Build-Tools

As I attempt to set up Windows-Build-Tools for my Electron project using NPM, I encounter an issue. When I execute npm install --global --production windows-build-tools, I receive the following error: Downloading python-2.7.15.amd64.msi Error: getaddrinfo ...

What is the best way to trigger a function after the v-model has been updated

When attempting to filter an array of objects in Vue using input, I encountered issues with Salvattore not functioning correctly for building a grid of the filtered elements. It seems that calling the rescanMediaQueries() function after changes to my v-mod ...

Material UI Alert component not appearing on screen?

Greetings, I have been working on polishing my app now that it is finally complete. I decided to enhance the aesthetics by replacing all instances of window.alerts with Alerts from MUI (since they look way better). However, for some reason, they are not sh ...

Issue encountered while running the command "npm start" on a recently generated project

I encountered an issue after creating a new ReactJS project and running "npm start" to launch it. This error has persisted across all my ReactJS projects, prompting me to create a new project to confirm that the error is not specific to one project. Here ...

Is there a way to retrieve the value from an input box?

<td class="stockQuantity"> <input class="form-control" id="Cart1" name="qty_req" required="required" type="text" value=""><br> <button type="button" o ...