0

I am dynamically loading some of the content within my page and would like to get a total of all the data-attributes.

First the elements are cloned and appended

$('.chip').on('click', function () {
  $(this).clone().appendTo('.chipPlacement');
});

Then I have written a function that should get the totals

function chipsBet() {
  var redchip = $('.chipPlacement .chipValue.r').data() || 0;
  var bluechip = $('.chipPlacement .chipValue.b').data() || 0;
  var orangechip = $('.chipPlacement .chipValue.o').data() || 0;

  var total = redchip.chipValue + bluechip.chipValue + orangechip.chipValue;
  return total;

}

Before I append the elements the HTML looks like

<div class="chipPlacement"></div>

and once appended the HTML structure is

 <div class="chipPlacement">
     <div class="chip red">
       <div class="chipValue r" data-chip-value="1">1</div>
     </div>
 </div>

I need to listen for the DOM structure the change and then fire the chipsBet() function, but I'm not sure how to get this to work. I can't use .on('change') as that only applies to input, textarea and select.

I have tried firing the chipsBet function within the .chip.on('click') but I get NaN returned.

How can I get the data-attribute-values for the new elements in the DOM?

Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
Richlewis
  • 15,070
  • 37
  • 122
  • 283

3 Answers3

2

If you don't have a blue or orange chip, you're effectively trying to get .chipValue from 0 which is undefined and adding it to another number gives you NaN.

You can simply iterate over all .chipValue elements within the placement element like so:

function chipsBet() 
{
  var total = 0;

  $('.chipPlacement .chipValue').each(function() {
    total += $(this).data('chipValue');
  });

  return total;
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

Nevermind, you altered your initial question.. carrying on.

<div class='chipPlacement'>
    <div class='chip red'>
        <div class='chipValue' data-chip-value='1'></div>
    </div>
</div>

Then to read your data attributes, you could do something like this.

$('.chip').on('click', function () {
    $(this).clone().appendTo('.chipPlacement');
    chipsBet();
});

function chipsBet() {
    var redchipVal = parseInt($('.chipValue .r').data('chip-value')) || 0;
    var bluechipVal = parseInt($('.chipValue .b').data('chip-value')) || 0;
    var orangechipVal = parseInt($('.chipValue .o').data('chip-value')) || 0;

    var total = redchipVal + bluechipVal + orangechipVal;
    return total;
}
BobbyDazzler
  • 1,193
  • 8
  • 21
0

I think you want something like bellow. It will call the function every time any change will in div .chipPlacement.

$('.chipPlacement').bind("DOMSubtreeModified",function(){
    console.log('Div modified');
});

You can say for your problem

$('.chipPlacement').bind("DOMSubtreeModified",function(){
     chipsBet();
});

DEMO

Mritunjay
  • 25,338
  • 7
  • 55
  • 68