Tips for organizing user information to generate a pie chart

My goal is to dynamically collect user input data from form input textboxes to create a pie chart when the submit button is clicked. Currently, I have a test version set up with fixed values displayed here:

<form style="margin-bottom: 50px;">
1 value: <input type="number" placeholder="In 100% percentage.." name="first" max="100"><br/>
2 value: <input type="number" placeholder="In 100% percentage.." name="second"max="100" ><br>
3 value: <input type="number" placeholder="In 100% percentage.." name="third" max="100"><br/>
4 value: <input type="number" placeholder="In 100% percentage.." name="fourth" max="100"><br>
</form>

<input type="submit" name="submit" value="Generate Pie-Chart" style="margin-bottom: 30px;">



<section>
<div>
<canvas id="canvas" width="400" height="300">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>

<script type="text/javascript">

var myColor = ["#ECD078","#D95B43","#C02942","#542437","#53777A"];
var myData = [100,30,20,60,40];

function getTotal(){
    var myTotal = 0;
    for (var j = 0; j < myData.length; j++) {
        myTotal += (typeof myData[j] == 'number') ? myData[j] : 0;
    }
    return myTotal;
}

function plotData() {
    var canvas;
    var ctx;
    var lastend = 0;
    var myTotal = getTotal();

    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (var i = 0; i < myData.length; i++) {
        ctx.fillStyle = myColor[i];
        ctx.beginPath();
        ctx.moveTo(200,150);
        ctx.arc(200,150,150,lastend,lastend+(Math.PI*2*(myData[i]/myTotal)),false);
        ctx.lineTo(200,150);
        ctx.fill();
        lastend += Math.PI*2*(myData[i]/myTotal);
    }
}

plotData();

</script>

However, I am seeking guidance on how to update the values in the var myData = [100,30,20,60,40]; array with the user's input from the form. Additionally, I am unsure of how to trigger the generation of the pie chart after the user clicks the generate button.

Answer №1

To improve accessibility, the first step would be to assign IDs to the form elements:

<form style="margin-bottom: 50px;">
1 value: <input type="number" placeholder="In 100% percentage.." id="first" name="first" max="100"><br/>
2 value: <input type="number" placeholder="In 100% percentage.." id="second" name="second" max="100" ><br>
3 value: <input type="number" placeholder="In 100% percentage.." id="third" name="third" max="100"><br/>
4 value: <input type="number" placeholder="In 100% percentage.." id="fourth" name="fourth" max="100"><br>
</form>

<input type="submit" name="submit" value="Generate Pie-Chart" style="margin-bottom: 30px;" id="plotSubmit">

Next, attach a handler to the submit button:

document.getElementById("plotSubmit").onclick = generatePie;

Now, define the handler function:

function generatePie() {
    // Retrieve values from inputs and store them in the data array:
    myData[1] = document.getElementById("first").value;
    myData[2] = document.getElementById("second").value;
    myData[3] = document.getElementById("third").value;
    myData[4] = document.getElementById("fourth").value;

    // Call plotData function again:
    plotData();
}

For a live demonstration, visit: http://jsfiddle.net/F5YRL/

Incorporating jQuery could streamline this process, but for now, this approach suffices.

Additionally, consider implementing data validation measures. Ensure all values are valid numbers and potentially evaluate if the sum must equal 100 or if all inputs must be filled.

These considerations can optimize the user experience.

Answer №2

My approach offers a unique solution that enables users to directly interact with the segments of the pie chart. It utilizes both d3.js and jQuery. I am open to any feedback!

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

Uh-oh, Ajax encountered a 500 Internal Server Error!

Utilizing ajax to fetch events from my database has hit a snag. Instead of displaying the results, there is nothing visible on the screen, and the console is showing this error message: POST http://www.example.com/system/live_filter.php 500 (Internal Se ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

Storing Documents on Your Device

I've been working on a project to create a web page that provides links to online PDF files. When you click on these links, the file should be saved locally and its name/path added to local storage. I then aim to display all the saved files by iterati ...

Methods for breaking down a number into individual elements within an array

Suppose there is a number given: let num = 969 The goal is to separate this number into an array of digits. The first two techniques fail, but the third one succeeds. What makes the third method different from the first two? num + ''.split(&ap ...

Tips for loading a webpage based on the selected value of a JQuery dropdown list

I'm currently working on an ASPX webpage where I am developing a feature to create reports using filter criteria. To populate my dropdown list, I am using a jqxwidget which retrieves values from a variable I have defined: var sourceRptType = [ ...

Issue encountered while attempting to send an HTML file using express.js

I have been trying to display an HTML file using Express.js with a static __dirname, but the HTML content does not show up after calling localhost/ var express = require('express'); var web = express(); ...

Automatically unselect the "initially selected item" once two items have been selected in Material UI

As someone new to web development, I'm struggling with a specific task. Here is the issue at hand: I have three checkboxes. If box1 and then box2 are selected, they should be marked. However, if box3 is then selected, box1 should automatically unchec ...

Adjust the opacity of a MeshBasicMaterial in real-time

<script type="importmap"> { "imports": { "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384c504a5d5d784e0816090e0a1608">[email p ...

Using ExpressJS and Jade to submit a form using the POST method and redirecting to a specified path

I am exploring node, express and jade for the first time and working on a small application that requires users to enter their name and password in a form. The app then redirects them to a path based on their username. Here is the code snippet to achieve ...

What are the best methods for implementing runtime type checking in JavaScript?

Utilizing either TypeScript or Facebook's Flow (type), I am empowered to statically assign types to variables like this: function add (x: integer, y: integer) { ... } Both TypeScript and Flow are able to identify and prevent incorrect invocations su ...

What is the proper way to write a function that verifies the presence of a key in an object and then retrieves the associated value?

After holding out for a while hoping to stumble upon the solution, I've decided to give it a shot here on SO since I haven't found it yet. import { PDFViewer, MSViewer } from './viewerclasses' //attempting to incorporate a union of key ...

Reassigning Click Functionality in AJAX After Initial Use

Encountering an issue with a click event on an AJAX call. The AJAX calls are nested due to the click event occurring on a div that is not present until the first AJAX call is made. Essentially, I am fetching user comments from a database, and then there ar ...

Exploring the capabilities of SVG and audio integration in web browsers

I am curious if it's possible to incorporate audio into an SVG file in a web browser. I came across this thread here, but unfortunately, I can't leave a comment =/ I tried implementing the code from this website, but it doesn't seem to work ...

The property 'clone' is undefined and cannot be read

Currently, I am using Fullcalendar to update events. My goal is to execute an ajax callback to retrieve the edited version of a specific event. The endpoint for this request should be at /controls/:id/edit. To achieve this functionality, I have implemented ...

Concealing HTML content with a modal overlay

There are security concerns with my authentication overlay modal, especially for users familiar with CSS and HTML. Is there a way to hide the HTML behind the modal so it doesn't appear in the page source? The code below is just an example of a modal ...

Error: Attempting to assign value to the 'innerHTML' property of null in a Wordle clone with local storage

While developing a Wordle-inspired game for my website, I decided to utilize Local Storage to store the user's progress. Everything seemed to be working smoothly until an unexpected error occurred: "Uncaught TypeError: Cannot set properties of null (s ...

An issue arises when attempting to remove or add attributes to the select box

In an attempt to change the 'disabled' and 'selected' properties, I am trying to set them to false and then apply the 'selected' and 'disabled' properties to the first option of a select box. Below is the code snippe ...

Utilizing Correlated Filters in Conjunction with Firebase Database

I am struggling with a firebase query that requires adding a where() condition based on a certain criteria. Specifically, I want the where() clause to be included only if certain values are entered, otherwise the basic query should run as usual. However, ...

Server encountered an unexpected T_STRING error that was not present on the localhost

While my website runs smoothly on localhost, I encounter the unexpected T_STRING error when running it on a workplace server with PHP 5.3.3. The culprit seems to be the exportXML function: eliminating this function resolves the issue. Any suggestions? I&a ...

Issue encountered while attempting to save hook arrays: Uncaught TypeError - 'choices' is not able to be

I'm in the process of creating a straightforward multiple-choice exam form that includes choices and answers. Whenever a user selects an option, it should be added to the array of choices. At the start, I have an array called exercises, which consist ...