Vaia Vaia - 1 month ago 6
jQuery Question

Dynamically create javascript values with given data-attributes?

I have build an dynamic ajax function that saves

data-xxx
-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;
and
var data_form = '#registerForm';
automatically.

How could I achieve this?

Answer

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) {
    e.preventDefault();
    console.log($(this).data())
  });
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href="#" data-index="1" data-form="#registerForm">send</a>

Comments