Search code examples
javascriptarraysfunctionobject

Accessing parameter from Javascript Function


I am using highcharts 4 javascript library. In highcharts, you can customize the buttons for the chart.

Chart with custom button

The way to do that is to push the buttons (as an object) in an array and then include this array in the Highcharts configuration.

The problem is that when I click on the button, I am having trouble accessing the parameters attached to each function

The code below shows how I create the array of buttons:

for(var i = 0; i < arr_papers.length; i++)
{
                var caption = arr_papers[i].caption;
                var colid = arr_papers[i].colid;
                
                buttons.push({
                    text: caption,
                    id : colid,
                    onclick: function () {
                        loadPerformanceBarChart(colid, caption);
                    }
                });
}

Then in the Highcharts configutation, I included the above array:

var options = {
            chart: {
                type: 'bar',
                renderTo: 'bar_chart_stats'
            },
            title: {
                text: 'Num Students per Range'
            },
            exporting: {
                buttons: {
                    contextButton: {
                        menuItems: buttons
                    }
                }
            },
.
.
.
.

The problem is that when the loadPerformanceBarChart function is called, the parameters colid, caption are the last ones from the array.

How can I find a way around? Thank you..


Solution

  • Declare the variables using let or const for block scoping.

    const caption = arr_papers[i].caption, colid = arr_papers[i].colid;