0

I want to use some string from an array and pass it into a function. The string has the same name as a global variable. From there, I want to set the output to the variable name. It is being passed to a slider function where the variable should update upon any changes.

I've tried passing it through [window] or eval(), but it does not work. Ideally, in the createSliders() function, on slide the global var would update.

i_current_annual_volume = 1000000;

let sliderArr = [{
   input: "i_current_annual_volume" (or window[i_current_annual_volume]),
   value: 1000000,
   min: 1000,
   max: 10000000,
   step: 1000,
}];

function createSliders() {
  for ( var i = 0; i < sliderArr.length; i++ ){
    let slider_name = "#slider-" + [i + 1];
    let handle_name = "#custom-handle-" + [i + 1];
    let input_field = sliderArr[ i ].input;

    $( slider_name ).slider({
      value: sliderArr[ i ].value,
      min: sliderArr[ i ].min,
      max: sliderArr[ i ].max,
      step: sliderArr[ i ].step,
      create: function() {
        $( handle_name ).text( $( this ).slider( "value" ) );
      },
      slide: function( event, ui ) {
        $( handle_name ).text( ui.value );
        input_field = ui.value;
      },
      stop: function(){
        loadNumbers();
      }
    });
  }
};



When I remove the quotes in the sliderArr, the output is 1000000. I need it to be i_current_annual_volume.

2 Answers2

1

You said you tried to use window, but you didn't show how you tried to do it. Global variables are properties of the window object. See Use dynamic variable names in JavaScript

Change

        input_field = ui.value;

to

        window[input_field] = ui.value;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Why should he.? – Rob May 30 '19 at 01:10
  • Added some explanation and a link to a more extensive question. – Barmar May 30 '19 at 01:15
  • @Rob I don't see why this answer wouldn't work. Although the author did mention having tried using `window`, there were no specifics given. – Pablo May 30 '19 at 01:38
  • 1
    @Pablo Rob didn't say it wouldn't work. He was just prompting me to add more explanation, rather than just posting the code. Since I frequently make similar comments to others, he caught me. – Barmar May 30 '19 at 01:40
0

Thanks for the help. I ended up creating an object array {} and passing the variable as string. That wound up being a simpler solution.