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?
1 Answer 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
5 Comments
Map.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.Explore related questions
See similar questions with these tags.
starter,advancedoreverything?