Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
});
like image 264
Nikolay Avatar asked Sep 02 '25 06:09

Nikolay


1 Answers

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.

like image 77
Toby Avatar answered Sep 04 '25 21:09

Toby