soum
soum

Reputation: 1159

adding up values from json

I am trying to add all the values from 'average_estimated_submitted_chargesand'

This is how I am doing it.

getting all the values by making a getJSON request and storing them in divs. and the then trying to read each and add them up. Not working. Returning NAN. (scroll down to the bottom of the fiddle to see the error)

var html = '';
var sum = '';

var dataUrl = 'http://data.cms.gov/resource/sq7j-n2ta.json';
$.getJSON(dataUrl, function(data){
    $.each(data, function(i){
        html += '<div class="billedCost">'+ data[i].average_estimated_submitted_charges + '</div>';
    });
    $('.holder').append(html);

    $('.billedCost').each(function(){
       sum += +this.value;
    });
    $('.total').append(sum);

});

Here is my fiddle

http://jsfiddle.net/sghoush1/uV6zy/5/

Upvotes: 0

Views: 975

Answers (3)

Lucas Lim
Lucas Lim

Reputation: 515

try this instead

var html = '';
var sum = 0;

var dataUrl = 'http://data.cms.gov/resource/sq7j-n2ta.json';
$.getJSON(dataUrl, function(data){    
$.each(data, function(i){
    html += '<div class="billedCost">'+ data[i].average_estimated_submitted_charges + '</div>`';
    sum += parseFloat(data[i].average_estimated_submitted_charges);
});

$('.holder').append(html);
$('.total').append(sum);

});

Fiddle: http://jsfiddle.net/aE6Bk/

Upvotes: 1

Sonu Sindhu
Sonu Sindhu

Reputation: 1792

Try this full code : HTML :

<div class="holder">Billed Cost</div>
<div class="total">Total</div>

SCRIPT :

var html = '';
var sum = 0;

var dataUrl = 'http://data.cms.gov/resource/sq7j-n2ta.json';
$.getJSON(dataUrl, function(data){
    $.each(data, function(i){
        html += '<div class="billedCost">'+ data[i].average_estimated_submitted_charges + '</div>';
        sum = sum+parseFloat(data[i].average_estimated_submitted_charges);
    });
    //alert(sum);
    $('.holder').append(html);

    $('.total').append(sum);

});

example

Hope it will help.

Upvotes: 0

Edward Groenendaal
Edward Groenendaal

Reputation: 81

Not sure why you added it up later - this is what I did in jsfiddle, using parseFloat();

var html = '';
var sum = 0;

var dataUrl = 'http://data.cms.gov/resource/sq7j-n2ta.json';
$.getJSON(dataUrl, function(data){
    $.each(data, function(i){
        html += '<div class="billedCost">'+ data[i].average_estimated_submitted_charges + '</div>';
        sum += parseFloat(data[i].average_estimated_submitted_charges);
});
    $('.holder').append(html);

    $('.total').append(sum);

});

Upvotes: 2

Related Questions