4

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();
});
Castro Roy
  • 7,623
  • 13
  • 63
  • 97
Nikolay
  • 225
  • 5
  • 12
  • Rel: http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – SEUH Jul 21 '16 at 23:33

2 Answers2

3

The correct syntax to target data attributes is:

var myVar = $(this).data("varName");

See here for more info:

https://api.jquery.com/data/

EDIT --

This doesn't address the issue of how to set the variable name, but it is the correct method for targeting data attributes.

Toby
  • 12,743
  • 8
  • 43
  • 75
  • I'm not using the jQuery data attribute, I am using HTML data-*. https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes Another reference: http://stackoverflow.com/questions/22113046/are-html-5-data-and-jquery-data-same-thing – Nikolay Jul 21 '16 at 23:05
  • Unless I'm misunderstanding something, jQuery now uses `.data` to target HTML5 data attributes - see this more detailed link: https://api.jquery.com/data/#data-html5. – Toby Jul 21 '16 at 23:08
  • Also, see this SO post for more info: http://stackoverflow.com/a/11673313/4008056 – Toby Jul 21 '16 at 23:11
2

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.

David Thomas
  • 249,100
  • 51
  • 377
  • 410