Vaia Vaia - 1 year ago 82
jQuery Question

Dynamically create javascript values with given data-attributes?

I have build an dynamic ajax function that saves

-values of elements to process the data. However I want to shorten this code which takes values depending on the ajax-request I want to process:

var data_form = $(element).attr('data-form');
var data_index = $(element).attr('data-index');
var data_hide_error = $(element).data('hide-error');
var data_disable_blur = $(element).data('disable-blur');
var data_hide_success = $(element).data('hide-success');

in a way that I only have one or two lines of code where I check which data-values are given in the element and if there is one data-value, I want to create a variable with that exact name.

For example: I click on this anchor
<a href="#" data-index="1" data-form="#registerForm">send</a>
and my function would create the variables
var data_index = 1;
var data_form = '#registerForm';

How could I achieve this?

Answer Source

Perhaps you meant this: Using .data() will return all data-attributes in one object to use in the function that you call

$(function() {
  $("a").on("click",function(e) {
<script src=""></script>
<a href="#" data-index="1" data-form="#registerForm">send</a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download