MrCycling
MrCycling

Reputation: 3004

Choosing specific array in javascript using value from html select

I have a number of arrays that contain multiple values.

 var ab = [".inb", ".bhm", ".bab", ".mdr"];
 var bc = [".thc", ".lsl", ".cma", ".vth"];
 var de = [".myh", ".rte", ".bab", ".tzs"];
    etc

I am using a select to specify which array to iterate through changing css values on a menu

 $('#browse2').on('change', function () {

    // the value of #browse2 would be ab or bc or de etc
    var fv = $('#browse2').val();

    for (i = 0; i < fv.length; ++i) {
       $(fv[i]).css('opacity', '1.0');
    }

 });

But unfortunately this code only goes through the fv value itself (ie: ab), it doesn't call the array with the same variable name. How do I tell the for statement to use the variable with the same name as the fv value?

Upvotes: 1

Views: 67

Answers (2)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12862

I would advice you to store arrays as properties of an object. You will be able to access them with the help of bracket notation:

var obj = {
     ab: [".inb", ".bhm", ".bab", ".mdr"],
     bc: [".thc", ".lsl", ".cma", ".vth"],
     de: [".myh", ".rte", ".bab", ".tzs"]    
 }; 

 $('#browse2').on('change', function () {   
    var fv = $('#browse2').val();

    for (i = 0; i < obj[fv].length; ++i) {
       $(obj[fv][i]).css('opacity', '1.0');
    }

 });

Upvotes: 2

Curtis
Curtis

Reputation: 103348

Change this line:

var fv = $('#browse2').val();

To:

var fvValue = $('#browse2').val();
var fv;
switch(fvValue){
   case "ab": fv = ab; break;
   case "bc": fv = bc; break;
   case "cd": fv = cd; break;
}

Basically in fv you were storing a string of "ab" rather than a reference to the ab array object.

Upvotes: 0

Related Questions