0

I want to extract data from data- tags within multiple class elements. Is the each() function the best way to do this?

Jquery:

$('#copymodal').on('show.bs.modal', function (event) {

            $(".copy19").each(function(){
                var a = data('total');
                alert(a);
            });
       })

HTML:

<a class='copy19' href='#'            
      data-statementid="14"
      data-total="98078"
      data-toggle="modal" 
      data-target="#editmodal">
      Edit
</a>

<a class='copy19' href='#'            
      data-statementid="16"
      data-total="78078"
      data-toggle="modal" 
      data-target="#editmodal">
      Edit
</a>

3 Answers3

1

extract data from data- tags within multiple class elements

Use .map() to get an array of values back: http://api.jquery.com/jquery.map/

var totals = $(".copy19").map(function(i, e) {
    return $(e).data("total");
}).get();

console.log(totals)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class='copy19' href='#'            
      data-statementid="14"
      data-total="98078"
      data-toggle="modal" 
      data-target="#editmodal">
      Link
</a>

<a class='copy19' href='#'            
      data-statementid="16"
      data-total="78078"
      data-toggle="modal" 
      data-target="#editmodal">
      Link
</a>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
0

Yes, each is one of the ways to do it as $('.copy19') returns a list of elements (basically an array).

deviprsd
  • 378
  • 3
  • 12
0
$(".copy19").each(function() {
    // Like this:
    var statementid = $(this).data('statementid');
    var total = $(this).data('total');
    var toggle = $(this).data('toggle');
    var target = $(this).data('target');

    // or like this..

    var allData = $(this)[0].dataset;
    /* value of allData is object with attributes:
    allData = {
        statementid: "14",
        total: "98078",
        toggle: "modal",
        target: "#editmodal"
    }
    */
});
evilReiko
  • 19,501
  • 24
  • 86
  • 102