Syden Syden - 23 days ago 9
jQuery Question

extract array value on click jQuery

Trying to achieve the following with

extractAssets();



  • When clicking on
    .clickable
    extract asset
    (lists[i].assets)
    value by itself to 0 (something like
    lists[i].assets - lists[i].assets
    ).



As you may see I'm not extracting but doing a .html("$0"), so a dynamic extraction would be desired.

see JSFiddle

Working fiddle example is appreciated, thank you.



var list1 = {
id: 7,
assets: 74651.90,
ratePercent: 0.02,
rateUSD: 24.03
};
var list2 = {
id: 8,
assets: 86735.79,
ratePercent: -0.06,
rateUSD: 2.41
};

var lists = [list1, list2];

$(document).ready(function() {
show();
extractAssets();
});

function extractAssets() {
for (var i = 0; i < lists.length; i++) {
//var text = $(".coin" + [i]).text();
$(".clickable" + [i]).click(function() {
//$(".coin" + [i]).text(text == $(this).text() - $(this).text() ? $(this).text() - $(this).text() : $(this).text());
$(this).find(".coin").html("$0");
//$(".coin" + [i]).text(text == $(this).text() ? "$0" : $(this).text());
})
}
}

function show() {
for (var i = 0; i < lists.length; i++) {
$(".DataContent").append('<div class="clickable' + [i] + '"><p class="data">' + lists[i].id + '</p><ul><li class="coin">$' + lists[i].assets + '</li><li class="rate"><span class="ratePercent">' + lists[i].ratePercent.toFixed(2) + '%</span> / <span class="rateUSD">$' + lists[i].rateUSD.toFixed(2) + '</span></li></ul></div>');
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="DataContent"></section>




Answer

Seems a bit weird to me that you're using the data for reference, but using the html dom elements for operations. I hardly recommend to us a templating language. Anyways... with your actual code this is what I would update:

function extractAssets() {
    $(".clickable").click(function(){
        var currentCoin = $(this).find('.coin');
      var difference = (Number($(currentCoin).text().replace('$','')) - Number($(currentCoin).text().replace('$','')));
      $(currentCoin).html('$' + difference);
        });
}

function show() {
  for (var i = 0; i < lists.length; i++) {
    $(".DataContent").append('<div class="clickable"><p class="data">' + lists[i].id + '</p><ul><li class="coin">$' + lists[i].assets + '</li><li class="rate"><span class="ratePercent">' + lists[i].ratePercent.toFixed(2) + '%</span> / <span class="rateUSD">$' + lists[i].rateUSD.toFixed(2) + '</span></li></ul></div>');
  }
}

Keep in mind that this does not format the amount at the end.

Regards