Passing a variable between functions in JavaScript: Tips and tricks

let chart;
let data = new Array();

function handleClick() {
    data = document.getElementById('graph:hi').value;
    alert(data);
}
let chartData = new Array(66, 15, 2.5, 21.9, 25.2, 23.0, 22.6, 21.2, 19.3, 16.6, 14.8);
alert(chartData);
jQuery(document).ready(function (e) {
    chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            defaultSeriesType: 'spline',
            ignoreHiddenSeries: false
        },
        title: {
            text: 'Height Report'
        },
        subtitle: {
            text: ''
        },
        xAxis: {
            categories: ['0', '0.5', '1.5', '2.5', '3.5', '4.5', '5.5', '6.5', '7.5', '8.5', '9.5', '10.5', '11.5', '12.5', '13.5', '14.5', '15.5', '16.5', '17.5', '18.5', '19.5', '20.5', '21.5', '22.5', '23.5', '24.5', '25.5', '26.5', '27.5', '28.5', '29.5', '30.5', '31.5', '32.5', '33.5', '34.5', '35.5']
        },
        yAxis: {
            title: {
                text: 'Percentage'
            },
            labels: {
                formatter: function () {
                    return this.value + '%';
                }
            }
        },
        tooltip: {
            formatter: function () {
                return '' + this.x + ': ' + this.y;
            }
        },
        plotOptions: {
            spline: {
                marker: {
                    radius: 3,
                    lineColor: '#666666',
                    lineWidth: 1
                }
            }
        },
        series: [{
            name: 'Pecentile 3',
            data: chartData
        }, {
            name: 'Pecentile 10',
            data: data
        }]
    });
});

This is an XHTML code snippet with a graph plotting functionality. The value obtained in the click() function is retrieved and passed to the jQuery function for graph plotting. However, there seems to be an issue with retrieving the values in the jQuery function. Thank you.

Answer №1

Your code appears to have a unique structure.

Why is there some code being executed before the document is ready and some inside the jQuery(document).ready(); function?

If you consolidate everything within the latter function, making necessary modifications, everything should function correctly.

I recommend:

  1. placing all code within the Query(document).ready(); function
  2. using a more jQuery style instead of function click(...), such as:

    $('graph:hi').click(function(){WRITE THE CODE});

  3. when doing this, ensure that d will be a global variable within your scope to avoid any issues you are facing

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

Using Lazy Load Plugin for jQuery to enhance Backbone.js functionality

I am working on a Backbone.js application using require.js and underscore.js. I am trying to incorporate the jquery lazy loading plugin with the Eislider banner. The Eislider banner was functioning properly before implementing the lazy loading script. Th ...

Alter Express routes automatically upon updating the CMS

Currently, I am working on a project that utilizes NextJS with Express for server-side routing. lib/routes/getPages const routes = require('next-routes')(); const getEntries = require('../helpers/getEntries'); module.exports = async ...

Leveraging the power of jQuery Ajax in conjunction with node.js and express for email validation functionality

Hey there! I have a contact form on my website that uses ajax for validation and email sending. The issue is that the validation file is set up for PHP, but I'm trying to make it work with my NodeJS app. Unfortunately, when I tried modifying the ajax ...

Invoke two functions simultaneously on a single Onchange event

Can someone help me understand how to trigger two functions by changing the value of a specific dropdown list using the "OnChange" event in Ajax? Note: The system typically only displays the output of the showhistory() function. Here is my existing code: ...

The post feature is not delivering the object as expected

I have created a Login page that is supposed to post Username and Password using Axios. I wrapped the username and password into an object as shown in the code below, but when I submit the form, I receive a "201" response. Everything seems to be working fi ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

"Trying to access the Reducer in a container results in an undefined value

I recently tried adding a new Container to my React App, connected it with Redux, and wanted to test if everything was functioning properly. Unfortunately, when I try to access the reducer using this.props.selection, it returns as undefined. This is puzzli ...

The module 'myapp' with the dependency 'chart.js' could not be loaded due to an uncaught error: [$injector:modulerr]

Just starting out with Angular.JS and looking to create a chart using chart.js I've successfully installed chart.js with npm install angular-chart.js --save .state('index.dashboard', { url: "/dashboard", templateUrl ...

What is the best way to ensure a jQuery function runs on duplicated elements?

I have been attempting to construct a webpage featuring cascading dropdowns using jQuery. The goal is to generate a duplicate set of dropdowns when the last dropdown in the current set is altered. I aim for this process to repeat up to 10 times, but I cons ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

What is the best way to attach several URLs to a single component?

I am currently using Next.js Here is the structure I have: https://i.stack.imgur.com/jRQBS.png I am in need of opening the same component for multiple URLs, such as 'http://localhost:3000/hakkimizda', 'http://localhost:3000/cerez-politika ...

Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try. Here is my initial attempt: var input = document.getElementById( ...

React.js issue with onChange event on <input> element freezing

I am experiencing an issue where the input box only allows me to type one letter at a time before getting stuck in its original position. This behavior is confusing to me as the code works fine in another project of mine. const [name, setName] = useStat ...

Switching the input type from file to text

My request is to have a file input type that is initially set as read-only, yet still allows the user to manually enter the file name in a text box. Is there a way to achieve this? I want to be able to write the file name similarly to how I would input t ...

step-by-step guide for resolving issues with downloading files in node.js

I've been attempting to download files from my server using node.js with the res.download function from Express, but I keep getting an undefined error. The folder path is D:\program\web\java_script\Node\my_project\ketabk& ...

Tips for efficiently updating state within a loop using the settimeout function in a React application

As I work on my react app to visualize sorting algorithms, I've encountered an issue that has me stumped. I am currently iterating through all elements of the array stored in the 'bars' state and attempting to swap them for testing purposes. ...

I have been utilizing ESBuild to compile JavaScript code for browser usage. However, I encountered an issue when trying to import CSS as I received an error message stating "Unexpected '.'". Can anyone provide guidance on how to resolve this issue?

I am currently developing a JavaScript notebook that operates within the browser environment. To compile my code, I have chosen to utilize ESBuild. My primary objective is to enable the handling of CSS imports such as <import 'bulma/css/bulma.css&a ...

Logging to the console using an If/Else statement, with the Else block containing code that

I'm encountering a peculiar issue with my If statement. I'm modifying the state (true/false) of an object based on onMouseEnter and onMouseLeave. I can execute the code when it's true, but if I include any code in the else statement, it ma ...

How to Retrieve a Remote File in Angular using $http.get() with OAuth Authentication

I have a unique situation where my users possess private files that require downloads by authenticated users. The server I am using initially downloads a file from S3 utilizing its own set of S3 app_id and secret_token credentials. Once the file has been d ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...