If you already have values in classes, jQuery already returns something that looks like an array, with all occurrences of that class... The classic method for dealing with this is the .each()
,
var tot = 0;
var n = 0;
$('.m').each(function(){
tot += parseInt( $(this).text() );
n++;
});
var MEDIA = tot/n;
However, for something as simple as calculating an average, the ideal would be to actually use an array, and this is also possible in jQuery, using the function makeArray()
,
var A = $.makeArray( $('.m') );
var Atot = 0;
for(i=0; i<A.length; i++)
Atot += parseInt(A[i].innerHTML);
var Amedia = Atot/A.length;
See http://jsfiddle.net/P3MhH/
NOTES
Javascript is not a language equipped with map/reduce to deal elegantly with arrays, but today, even with a small cost of performance, it is already possible to make use of array filter and aggregation functions. The average is a typical aggregate, and can be expressed with these resources, see this other jsFiddle:
var A = $.makeArray( $('.m') ).map(function(a) {
return parseInt(a.innerHTML)
}); // ou $('.m').map(function(){ return parseInt($(this).html()) }).get();
var soma = A.reduce(function(a,b) {return a + b});
var media = soma / A.length;
This way of expressing an array algorithm is still little used, some people find unintelligible, "mathematical thing"... I try to avoid prejudices. One can, for example, use in formal specifications.
Access to tag values <input>
, the easiest in jQuery is the .val
... For other tags (typically <span>
as I exemplified in jsfiddle) the use of nodeValue can be faster, see https://stackoverflow.com/a/18418270/287948
What is inside the html? numbers? And how many
.deztotal
can there be? only one?– Sergio
within html is the separated mysql database values within a table per month!
– Alan PS
and are the months of the year that will generate the average, are 12 fields to calculate the average!
– Alan PS
Put your HTML and you’ll get an answer, so it’s hard to guess what your HTML looks like.
– Sergio
put html!! help ?
– Alan PS
Add all and divide by 12, Ué!
– bfavaretto
@bfavaretto is true, just add everything and divide by 2!!! I traveled!!!
– Alan PS
Ops, your HTML is inconsistent.. besides compromising the use of the attribute
id
(needs to be unique), is not using the same class for all items of the desired average.– Peter Krauss
The problem there is that you should use jQuery.val() and not jQuery.html(). If you want it to be dynamic (not just 12) divide by the value of the property length. just taking care not to be by zero. And If it is not possible to change the HTML (which I doubt) may instead search for the class, seek for the attribute name.
– Bruno Augusto
@Peterkrauss and Bruno Augusto, I will correct the mistakes, Valew by the answers!!!
– Alan PS