从变更输入中获得平均值

Hug*_*ugo 0 jquery

我想通过输入值得到平均值,我有5个输入字段.这是我发现的,但它不是使用onchange事件的输入,有人可以帮助我吗?

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);
Run Code Online (Sandbox Code Playgroud)

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

sde*_*ont 5

您可以使用keyup此类事件,并在考虑之前检查输入值是否为数字

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);
});
Run Code Online (Sandbox Code Playgroud)

  • 这是对的,但你可能想解释为什么要帮助OP了解他做错了什么. (2认同)