Oneezy
Oneezy

Reputation: 5013

How to pull in data by using a data-attribute?

I'm trying to pull in data from our API with a data- html trick.. I can call the data directly and it load just fine. But when i try to get the data variable from the data attribute it won't work.

Is there something flawed in my code?

i.e.

<span id="totalBalanceBTC" data-api-user-getbalance="totalBalance">--</span>
function dataAPI() {
    let balanceUrl = 'https://api.example.io/v1/user/getbalance/username';
    let balanceApiData = getApiData(balanceUrl);

    $('[data-api-user-getbalance]').each(function (){

      let dataUserBalance = $(this).data("api-user-getbalance");
      let data = balanceApiData.dataUserBalance;

        // WORKS
        $(this).html(balanceApiData.totalBalance);

        // DOES NOT WORK
        $(this).html(balanceApiData.dataUserBalance);

    });
  }

Upvotes: 0

Views: 33

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

1. jQuery's .data() drops the data- prefix and converts the remaining hyphenated string to camelCase, using the dashes as delimiters. It should be:

let dataUserBalance = $(this).data("apiUserGetbalance");

2. To access an object property using a variable, you'll need to use bracket notation. Otherwise you're trying to get the property "dataUserBalance", which doesn't exist.

let data = balanceApiData[dataUserBalance];

const balanceApiData = { totalBalance: 500 };
const $elem = $("#totalBalanceBTC");

let dataUserBalance = $elem.data("apiUserGetbalance");
let data = balanceApiData[dataUserBalance];

console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="totalBalanceBTC" data-api-user-getbalance="totalBalance"></span>

Upvotes: 1

Related Questions