0

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?

2
  • 1
    so, contract will be either starter, advanced or everything? Commented Aug 7, 2016 at 8:51
  • yes. one of those 3 names. Commented Aug 7, 2016 at 8:52

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Or in ES2015+, using a Map.
Please explain rather than just posting code. Before posting the answer, not later as an edit.
well, looking at the original code, I assumed he was so close he didn't need too much explanation
@T.J.Crowder - you should post an ES2015+ answer - I'd be interested in why map is a better alternative
I'm not sure it is better in this case. The main advantages Map has over using an object are: 1. No potential conflict with inherited properties (but that can be mitigated using Object.create(null) to create the object), and 2. Keys can be things other than strings. In this case, there's no possibility of conflict, and the keys are strings, so... So Map is an alternative, but I'm not arguing that it's better.

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.