user11249486
user11249486

Reputation:

Jquery select multiple classes and extract data

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>

Upvotes: 0

Views: 276

Answers (3)

evilReiko
evilReiko

Reputation: 20483

$(".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"
    }
    */
});

Upvotes: 0

deviprsd
deviprsd

Reputation: 378

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

Upvotes: 0

fdomn-m
fdomn-m

Reputation: 28621

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>

Upvotes: 1

Related Questions