0

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?

4
  • Please elaborate. Your question is not clear. Also you have $(element).attr('data-form'); when $(element).data('form'); will suffice Commented Nov 2, 2016 at 13:18
  • I know, that was just an example. Also I stated my question very precisely. I want to save the data-attribute-values in a javascript variable if there is a data-attribute-value of a specific data-attribute. And this variable should have the same name as the data-attribute. Commented Nov 2, 2016 at 13:20
  • 1
    You can use $(element).data(); to get all data- attributes from element as object Commented Nov 2, 2016 at 13:21
  • Beat me by 13 seconds :) Commented Nov 2, 2016 at 13:23

1 Answer 1

2

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>

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

1 Comment

Thank you! I didn't know this.

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.