Setting global variable values when a button is clicked in Javascript

My query involves JavaScript. I have an HTML template with a button (b1) that, when clicked, assigns an array to a variable called tempdata. The issue arises when trying to display this tempdata array using alert() outside the onclick function; nothing happens. However, if I try the alert inside the onclick function, it works as expected. My requirement is to use the tempdata array outside the onclick function in order to pass it to the data tag for the config variable.

So, my question is: How can I set the tempdata array and successfully pass it to the data tag?


var cusomernames=[];

var myObj = [{
"region":"APAC",
"customers": [
    { "name":"A", "count":100 },
    { "name":"B", "count":35 },
    { "name":"C", "count":90 }
]
},
{
"region":"ASEAN",
"customers": [
    { "name":"A", "count":30 },
    { "name":"B", "count":35 },
    { "name":"C", "count":90 }
]
}

];

function myFunction() {
    var datasum=[];  
    for(var i = 0; i < myObj.length; i++) {
        if(myObj[i].region == "APAC"){
            for(var p=0;p<3;p++){
                datasum.push(myObj[i].customers[p].count);
                cusomernames.push(myObj[i].customers[p].name);
            }
        }

    }

    return datasum;        
}

window.onload = function() {
    var b1=document.getElementById('b1');
    var tempData=[];
    b1.onclick=function(){  
        tempData=myFunction();
        alert(tempData);
    }

    var config = {
        type: 'funnel',
        data: {
            datasets: [{
                data: tempData,
                backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ]
            }],
            labels: ["A","B","C"]
        },
        options: {
            responsive: true,
            sort: 'desc',
            legend: {
                position: 'top'
            },
            title: {
                display: true,
                text: 'Chart.js Funnel Chart'
            },
            animation: {
                animateScale: true,
                animateRotate: true
            }
        }
    };

    var ctx = document.getElementById("chart-area").getContext("2d");
    window.myDoughnut = new Chart(ctx, config);

};

Answer №1

Is it possible to bypass using a temporary variable and directly assign the config attribute?

//....
var config = {...}
window.onload = function () {
    b1.onclick(function () {
        config.datasets[0].data = myFunction();
    });
    //Chart stuff
}

Answer №2

Consider trying this:

tempData.push(myFunction());

Instead of doing this:

tempData=myFunction();

Update: Both methods mentioned above should work fine, possibly depending on timing. It might be beneficial to place the config within the scope of the event listener like this:

b1.onclick=function(){  
    tempData=myFunction();
    alert(tempData);

    var config = {
        type: 'funnel',
        data: {
            datasets: [{
                data: tempData,
                backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ]
            }],
            labels: ["A","B","C"]
        },
        options: {
            responsive: true,
            sort: 'desc',
            legend: {
                position: 'top'
            },
            title: {
                display: true,
                text: 'Chart.js Funnel Chart'
            },
            animation: {
                animateScale: true,
                animateRotate: true
            }
        }
    }; 
}

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

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

Get the package from a Lerna-managed monorepository using a git URL

Currently working on a project using yarn. The project has a dependency that is part of a larger monorepo managed by lerna. Despite the subpackage being updated, it has not been published yet and I require access to that unreleased code. Is there a method ...

Show or hide the expand/collapse button based on the height of the container

Looking for a way to hide content in a Div if it's taller than 68px and display an expand option? The challenge lies in detecting the height of the responsive Div, especially since character count varies. I attempted using PHP to count characters bu ...

Having difficulty assigning a value to a specific element within an array

When a button labeled "update" is clicked in an array called admin, I would like to display a div. The goal is for the div to appear below the selected element only and not affect any others in the array. function Admin(props) { const [showMe, setShowMe ...

changing the contents of an array within the current state

My current task involves updating a list of names in the state before sending it as props to another component. // code snippet omitted for brevity this.state = { // other states here playerName: { player1Name: 'Default Player 1 Name ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

What is the best way to retrieve AJAX responses from JSON data that contains multiple sets of information

["12-Feb-2017","06-Feb-2017","5","45","40","Neha shishodia","USD","unit2","phase1","Change Request","Client Approval Awaited"]["07-Feb-2017","04-Feb-2017","6","54","48","Neha shishodia","USD","unit2","phase1","Change Request","Manager Approval Awaited"] T ...

Tips for accessing id from $http.get in angular.js

Hello everyone, I'm new to Angular.js and currently learning it. I need help in retrieving data from the following API URL: . I am unsure how to implement this in my controller.js file. Below is the code I have so far, can someone please guide me on h ...

The Ion-button seems to be malfunctioning

I am interested in using special buttons for my ionic 1 project, specifically the ion-button feature outlined on this page: Ionic Buttons. I attempted to create a Round Button and an Outline + Round Button: <h2 class="sub-header" style="color:#4 ...

Look for and choose various fields from a lengthy JSON object

I am working with a JSON object that contains a large list of offerValue objects. { "Code": 0, "response": "SUCCESS", "offerValue": [ { "id": "111", "name": "ABC", "flag": "V" }, { ...

Focus issue with MUI Custom Text Field when state changes

Currently, I've integrated the MUI library into my React Js application. In this project, I'm utilizing the controlled Text Field component to establish a basic search user interface. However, an unexpected issue has surfaced. Following a chang ...

Exploring the intersection of JavaScript and PostgreSQL: Leveraging timezones and timestamps

I'm a bit confused about how to properly use timestamps. For example, when a user creates an article, they can choose a PublishDate, and the system also automatically stores a CreateDate. a. Should I make both PublishDate and CreateDate timestamps wi ...

Creating a Dual Y-Axis Chart with Two Sets of Data in chart.js

I utilized the chart.js library to write the following code snippet that generated the output shown below. My primary concern is how to effectively manage the labels on the horizontal axis in this scenario. CODE <!DOCTYPE html> <html lang="en"& ...

Guidelines for incorporating Context API in Material UI

Currently, I am encountering a TypeScript error while attempting to pass a property using the Context API within my components. Specifically, the error message reads: "Property 'value' does not exist on type 'String'" To provide conte ...

What is the best way to include a new user in the memory database when there is no database or storage back-end?

During an online test, I was given the task of adding a user to a database stored in memory. The request body required JSON formatting as shown below: { "id": "aabbbccddeeefff", "name": "User One", "hobbies": [ "swim", "sing", "workout" ] } (Users ...

What is the best way to inject child nodes into parent nodes without causing the view to shift to the location where the element is being

While I am rendering elements and appending them to a parent div, my screen keeps jumping to the bottom-most element as it loads instead of maintaining the current view. Ideally, it should start at the top of the screen and remain there without any sudden ...

Is there a way to use Axios to send several HTTP requests to a URL simultaneously, but pause once a response is received from any one of the requests?

As a beginner in javascript, I am working on writing a script that will use Axios to send multiple HTTP requests to a web server. The server randomly responds to the requests, and I want the script to stop sending requests once it receives a response. This ...

Serve an image in Node.js from a location outside of the public folder

Is there a way to display an image that is located outside of the public folder in my webroot? Here is my directory structure: Webroot --core ----views ----public <- Stylesheets and other images are stored here ------index.ejs <- I want to display f ...

There are times when window.onload doesn't do the trick, but using alert() can make

I recently posted a question related to this, so I apologize for reaching out again. I am struggling to grasp this concept as I am still in the process of learning JavaScript/HTML. Currently, I am loading an SVG into my HTML using SVGInject and implementi ...