1

I have several javascript sliders on a page and I want to be able to enable or disable each by using a variable.

For example, I have a slider:

var slider1 = new Slider('#sitSlider', {
                       formatter: function(value) {
                                return  value;}     });

and I enable/disable it with this:

        slider1.disable();

I would like to be able to do something like this to turn off several switches:

for(x=0;x<20;x++){
    var tmpStr = "slider"+x;
tmpStr.disable();
}

I did some searching and tried this without success:

this[tmpStr].disable();

How do I go about using a variable to call an object? Thanks.

Edit: Here's the slider component I'm using: Bootstrap Slider

Sadie
  • 121
  • 1
  • 7

2 Answers2

1

Create an array:

var sliders = [];

Push your objects onto that array:

sliders.push(new Slider(...));

Then in your loop you can access the array elements:

for(x = 0; x < sliders.length; x++){
    sliders[x].disable; // side note: missing parentheses here?
}

Any time you're trying to use an incrementing number as part of a variable name, you're probably looking for an array or collection of some kind.

David
  • 208,112
  • 36
  • 198
  • 279
  • When I try that, I get "TypeError: TypeError: sliders[x].disable is not a function. (In 'sliders[x].disable()', 'sliders[x].disable' is undefined)" The missing parentheses were just in typing my question... thanks. – Sadie Apr 18 '17 at 18:15
  • @user3092108: Then `disable()` is not a function on your objects. I can't really speak to what the objects themselves are or how they're defined, just how to access them in an array as asked in the question. – David Apr 18 '17 at 18:17
  • Hmm... slider1.disable() by itself works. I added a link to the component to the bottom of my question. The disable/enable functions begin at line 973. Does that help? – Sadie Apr 18 '17 at 19:06
  • @user3092108: You might update the question with specific code that produces the issue. Could be a problem with adding the object to the array? – David Apr 18 '17 at 20:04
1

No. You cannot do that. Variable name shouldn't be given like that.

The easiest you can do create an array and push your sliders. And you can loop the array and access the sliders.

var sldsr =[];

...
sldsr.push(slider1);

...

sldsr.push(slider2);

for(x=0;x<sldsr.length;x++){

  sldsr[x].disable();

}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307