Hugo
Hugo

Reputation: 23

Get average from inputs on change

I want to get the average by input value, and I have 5 input fields. This is what I found but it is not with inputs using an onchange event, can someone help me with that?

var total = 0,
    valid_labels = 0,
    average;

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

average = total / valid_labels;
$('.average').val(average);

jsfiddle http://jsfiddle.net/Pqd8B/1/

Upvotes: 1

Views: 867

Answers (1)

sdespont
sdespont

Reputation: 14025

You can use the keyup event like this and check if the input values are number before taking into account

http://jsfiddle.net/Pqd8B/2/

// Catch all inputs key events : recalculate average
$('.td_input').keyup(function () {

    // Init variables
    var total = 0,
        valid_labels = 0,
        average;

    $('.td_input').each(function () {
        // Retrieve input value
        // .innerHTML only retrieves the info between the HTML tags, and is
        // a non-jQuery call.  The jQuery version is .html(), but you want 
        // .val() with no parameters, which gets the current input value
        var val = parseInt($(this).val(), 10);

        //Test if it is a valid number with built-in isNaN() function
        if (!isNaN(val)) {
            valid_labels += 1;
            total += val;
        }
    });

    // Calculate the average
    // Note: This is done inside the keyup handler
    // When it is outside, it is only calculated once when the page loads
    $('.average').val(total / valid_labels);
});

Upvotes: 6

Related Questions