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

Put a spinner within a JavaScript function

Implementing a spinner using JavaScript function. Hello everyone, I am new to JavaScript and I am struggling to include a spinner in my code. Below is the code that I wrote. Can anyone help me identify what the issue might be? document.getElementById(&apo ...

What methods can be used to customize the font and background color of a website for different user groups?

Trying to incorporate a template into my project. My client has requested the following: The regular user area should feature a blue background. The professional user area should have an orange background. Is there a way to set up a condition to change ...

I keep receiving a JavaScript alert message saying "undefined."

When I try to alert the item_id after giving input in the quantity textbox, I am receiving an undefined JavaScript alert. The code snippet below is not displaying the alert as expected: var item_id=$("#item_"+i).val();alert(item_id); In addition, my mode ...

Obtain a nested array of objects from Mongoose's Model.find() method and then make modifications to the inner array

I need to retrieve an array of objects with a specific ID from my database within a server route, and then update a property of an object within that array (rather than returning just the objectID, I want to return the Document as an object with the specif ...

Guide to authenticating Cashfree gateway's webhook signature using JavaScript

I have integrated the Cashfree payments gateway successfully. However, I am unsure how to verify the signature of webhooks. https://i.stack.imgur.com/TxdTx.png This is their recommended approach. Could someone guide me on writing JavaScript code for this ...

Any idea how to dynamically insert rows and columns into a table or div element?

Can anyone assist me with this task? I have successfully completed the visual process I intended to do. How can I achieve this structure using AngularJS? The data will be stored in Json format. When the "+" symbol is clicked in a certain direction, the fi ...

Is it necessary to generate a file for each API in Next.js?

When working with Next.js, it is common practice to create a separate file for each new API endpoint. For example, for the /user endpoint, there would be a user.js file with its own handler, and another one for /user/goldmember. Some may argue that this ...

Perform an asynchronous reload of DataTables using ajax.reload() before calling a function

I need help extracting real-time data from a datatable and populating a form for editing when an edit button is clicked on each row. Despite my efforts, the ajax.reload() function doesn't load the table in time to fill the form with correct data. The ...

"OBJLoader Three.js r74, bringing vibrantly colored elements to your 3

It's a straightforward process, I import my OBJ model that was exported using 3DS Max. I have the intention of coloring a specific section of the Object. During the animation loop, I implement the following: scene.traverse( function( object ) { ...

Installation of the package was unsuccessful: npm encountered an error with code ERESOLVE, indicating that it was unable to destructure the property 'name' from 'node' as it is currently null

Mohameds-MacBook-Air:client sakeeljawfer$ ng add @ng-bootstrap/ng-bootstrap ℹ Using package manager: npm ✔ Found compatible package version: @ng-bootstrap/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a ...

Utilizing AngularJS ng-repeat, generate dynamic HTML content by calling a function to retrieve data

Just starting out with angularjs and trying to unravel the mystery here. Using ng-repeat: <li class="widget flip-container" ng-repeat="widget in widgets"> <div class="widgetContent" ng-bind-html="getData(widget.UserWidgetId,widg ...

The entire DOM has been seamlessly replaced by React.JS within the Node.js server

I am currently focusing on practicing the MERN structure, so my goal was to start by setting up a node.js server and react front-end. However, I encountered an issue where the entire DOM gets overwritten once the server is fired up. This has left me wonde ...

Utilize React to Effectively Control Multiple Audio Files on a Single Page, Ensuring Only One Plays at a Time with Function

I am currently working on a new React app that includes multiple music cards on the same page. I am looking to modify the state of the previous card before updating the state of the new card. Essentially, I aim to pause the audio playing in the previous ca ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

Load Form with Json Data from LocalStorage Key-ID to Auto-Populate Fields

After successfully setting the ID in localStorage, I now need to retrieve and display only that specific record from my JSON data. The content of my localStorage is: This information is obtained from my JSON data after a button click. The challenge is us ...

Retrieve the link's "href" attribute and its text if they match the specified text

Is there a way to extract the href link and text from a specific type of link? <a href="google.com">boom</a> I am looking to retrieve only the 'google.com' part and the text 'boom' Furthermore, how can I filter out other ...

JavaScript CheckBox Color Change Not Functioning

Hello, I am currently experimenting with the checkAll function. When I click on the checkAll checkbox, it should select all rows and change their background color accordingly. Below is the JavaScript code I am using: function checkAll(objRef) { v ...

Send information to a function until the array reaches its maximum length

I am facing a challenge where I have a function that accepts multiple arrays as arguments, but the data available to me is already within an array called mainArr. This mainArr consists of several array items that need to be passed as arguments to the funct ...

Guide to configuring browserify

After installing the modules (browserify, react, reactify), I attempted to process a JSX file using browserify. var React = require("react"); var App = React.createClass({ render: function () { return <h1>111</h1> } }); React ...

Copying to the clipboard now includes the parent of the targeted element

Edit - More Information: Here is a simplified version of the sandbox: https://codesandbox.io/s/stupefied-leftpad-k6eek Check out the demo here: The issue does not seem to occur in Firefox, but it does in Chrome and other browsers I have a div that disp ...