One option is to store your variables in an object, and then use object-notation to assign values to variables:
<form>
<input data-varName="test1" />
<input data-varName="test2" />
</form>
var allVariables = {};
$('form input').each(function(){
allVariables[ $(this).data('varName') ] = $(this).val();
});
Or, in plain JavaScript:
Array.from( document.querySelectorAll('form input') ).forEach(function(el) {
allVariables[ el.dataset.varName ] = el.value;
});
Which, given the above HTML, would result in an allVariables
object like:
{
'test1' : test1Value,
'test2' : test2Value
}
Obviously, you could also use the window
global object, and register variables to that instead but that carries the concern that variables of the window
object are global and can be over-written by plugins elsewhere in the code.