0

As you see I have more than one data-record-* attribute and I want to get value of these attribute using by each function with the help of jquery.

but I want to get of these value automatically with jquery for example attribute begins with ``data-record`.

I will post these value with jquery/ajax

$('a').on('click',function(){
  var el = $(this).data();
  el.each(function(e){
    alert(el);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-record-id="1" data-record-name="section-1" data-record-order="short" class="ajax">Click on me!</a>
ani_css
  • 2,118
  • 3
  • 30
  • 73

3 Answers3

1

Just remove the loop; I think this is what you're looking for?

$('a').on('click',function(){
  
  var TheData = $(this).data();

  for (var key in TheData) {

     console.log(TheData[key]);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-record-id="1" data-record-name="section-1" data-record-order="short" class="ajax">Click on me!</a>
frenchie
  • 51,731
  • 109
  • 304
  • 510
  • if I use like this: `$('a').on('click',function(){ var el = $(this).data(); alert(el) });` this return object object I need one by one with alert or with in a list item doesn't matter I will post these data with ajax that's why I'm asking – ani_css Jun 29 '17 at 10:57
  • Ah ok, well then see updated answer; once you've got the data in an object, just loop through the keys. Try it; it works. – frenchie Jun 29 '17 at 11:00
  • work very well so I will try the post this value with ajax is that possible one by one ? so is that correct way `$('a').on('click',function(){ var myData = $(this).data(); $.each( myData, function( index, value ) { $('ul').append("
  • "+ "index: " + index + "value: " + value+"
  • " ); $.ajax({ url:value, method: "post", success: function(data) { } }); }); }); ` – ani_css Jun 29 '17 at 11:06
  • It could work, hard to say because it depends on how your back-end will process it. But I don't recommend doing it this way because you're making several calls when you could just be making one ajax call. In the loop over the object keys, I'd build an array with the keys of the object and then ajax that array. – frenchie Jun 29 '17 at 13:12