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.
0

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Why should he.?
Added some explanation and a link to a more extensive question.
@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 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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.