Search code examples
jqueryaveragejquery-calculation

jQuery - calculate average from span tags and output in a text field


I just started with jQuery and I'm having some troubles. I need to get a number between span tags, and output an average in an input field. Only the spans with a value different from 0 are valid , otherwise they should be ignored. Also the numbers can change anytime and the average must update without page reloading.

RELEVANT HTML

<div>
    <span class="pm_label">5</span>
</div>
<div>
    <span class="pm_label">10</span>
</div>
<div>
    <span class="pm_label">0</span>
</div>

<input type="text" name="average" class="average" value="">

NON WORKING JS:

jQuery( document ).ready( function($) {

    var sum = 0; 
    var nums = 0;

     $('.pm_label').each(function(){

        var value = $(this).html()

        if(value != 0) {

            sum += value;
            nums++;
        }
     });

     var avg = sum / nums ; 

     $('#average').val(Math.floor(avg));
     console.log(avg);

});

Thanks for your help


Solution

  • To get you started:

    var total = 0,
        valid_labels = 0,
        average;
    
    $('.pm_label').each(function () {
        var val = parseInt(this.innerHTML, 10);
        if (val !== 0) {
            valid_labels += 1;
            total += val;
        }
    });
    
    average = total / valid_labels;
    $('.average').val(average);
    

    Here's a DEMO

    You could make this into a function and call it whenever the spans' value change.