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();
});
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not using the jQuery data attribute, I am using HTML data-*. developer.mozilla.org/en-US/docs/Web/Guide/HTML/… Another reference: stackoverflow.com/questions/22113046/…
Unless I'm misunderstanding something, jQuery now uses .data to target HTML5 data attributes - see this more detailed link: api.jquery.com/data/#data-html5.
Also, see this SO post for more info: stackoverflow.com/a/11673313/4008056
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.

1 Comment

Actually this would work for what I need. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.