Arthlete Arthlete - 4 months ago 10
HTML Question

html "data-" attribute as javascript variable

Is it possible to register a html data-attribute as the name of a javascript variable?

What I am talking about is something like this:

<form>
<input data-varName="test1" />
<input data-varName="test2" />
</form>

$('form').find('input').each(function() {
var $(this).attr('data-varName') = $(this).val();
});

Answer

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.