Currently I have a bunch of variables that a dozen functions need access to. Here’s a snippet, but the list is bigger than this.
let highSchoolChecked = document.getElementById('highSchoolPack') .checked;
let forRentChecked = document.getElementById('forRentPack') .checked;
let horseRanchChecked = document.getElementById('horseRanchPack') .checked;
let growingTogetherChecked = document.getElementById('growingTogetherPack').checked;
let cottageLivingChecked = document.getElementById('cottageLivingPack') .checked;
let snowyEscapeChecked = document.getElementById('snowyEscapePack') .checked;
let ecoLivingChecked = document.getElementById('ecoLivingPack') .checked;
There seems to be only two ways to get the functions to register them:
function function1() {
let highSchoolChecked = document.getElementById('highSchoolPack').checked;
let forRentChecked = document.getElementById('forRentPack') .checked;
let horseRanchChecked = document.getElementById('horseRanchPack').checked;
}
// or
function function2( highSchoolChecked, forRentChecked, etc )
Is there an easy way to gain access to these where I just have to call one variable rather than 2 dozen?
e.g
function variablesList(){
let highSchoolChecked = document.getElementById('highSchoolPack') .checked;
let forRentChecked = document.getElementById('forRentPack') .checked;
let horseRanchChecked = document.getElementById('horseRanchPack') .checked;
let growingTogetherChecked = document.getElementById('growingTogetherPack').checked;
let cottageLivingChecked = document.getElementById('cottageLivingPack') .checked;
let snowyEscapeChecked = document.getElementById('snowyEscapePack') .checked;
let ecoLivingChecked = document.getElementById('ecoLivingPack') .checked;
}
I tried function function1(variablesList) but it didn’t seem to work. All the different functions are on different js files.
2
Answers
You can
return
anobject
of these values from a function, and call this function when you need these values. and because these functions are in differentjs
files, you need to make sure thegetVariableStates
function is globally accessible and one solution to this is to attach it to thewindow
global object.When you need these values.
You can capture the DOM element
checked
states in a single object using a CSS selector andObject.fromEntries