0

I have this:

$(document).ready(function() {
    $('input[type="button"]').click(function() {
        var sum = 0, count = 0, result;

        $('input[type="text"]').each(function() {
            var val = Number( $(this).val() );
            if (val && val >= 0) {
                sum += Number(val);
                count++;
            }
        });
        the error is that it does not take zero into account,
        for example, 10 and 0 should average out to 5, not 10.
        result = (count > 0) ? sum/count : 'no values found';
        $('#result').html( result );

    });
});

How can I make it account for the number 0 when it figures out averages?

2
Contributors
1
Reply
14
Views
4 Years
Discussion Span
Last Post by paulkd
0

Move count out of the if(val

        $('input[type="text"]').each(function() {
            var val = Number( $(this).val() );
            if (val && val >= 0) {
                sum += Number(val);
            }
            count++;
        });

Edited by paulkd: incorrect alignment

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.