Reputation: 1
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.
Upvotes: 0
Views: 52
Reputation: 1
Thanks for the help. I ended up creating an object array {} and passing the variable as string. That wound up being a simpler solution.
Upvotes: 0
Reputation: 780869
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;
Upvotes: 1