Reputation: 1159
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
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
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);
});
Hope it will help.
Upvotes: 0
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