Archer
Archer

Reputation: 1124

Access array elements of dynamic arrayname

I've got a lot of modules with checkboxes which I want to check, using an array. There are 3 packages with several modules. I generated a dropdown with the package names. After I choose a package, the checkboxes should get checked.

But I have a problem with the generated array name. I can't access it.

$("#package").change(function () {
    var starter = ["module1", "module2", "module3"];
    var advanced = ["module1", "module2", "module3", "module4", "module5"];
    var everything = ["module1", "module2", "module3", "module4", "module5", "module6", "module7"];    

    var contract = $('#package').val().toLowerCase();
    var arname = {};

    $.each(arname[contract], function( index, name ){
      $( "#module_" + name).prop('checked', true);  
    });     
});

How can I choose the array name, depending on the value of the dropdown #package?

Upvotes: 0

Views: 32

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

rearrange your code slightly, like this

$("#package").change(function () {
    var arname = {
        starter: ["module1", "module2", "module3"],
        advanced: ["module1", "module2", "module3", "module4", "module5"],
        everything: ["module1", "module2", "module3", "module4", "module5", "module6", "module7"]
    }
    var contract = $('#package').val().toLowerCase();

    $.each(arname[contract], function( index, name ){
      $( "#module_" + name).prop('checked', true);  
    });     
});

which makes an object, arname, with properties starter, advanced, and everything

you can access those exactly like your original code

Upvotes: 1

Related Questions