从变化的输入中获取平均值 [英] Get average from inputs on change

查看:109
本文介绍了从变化的输入中获取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过输入值获取平均值,并且我有5个输入字段. 这是我发现的,但不是通过onchange事件输入的,有人可以帮我吗?

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/

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

推荐答案

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

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);
});

这篇关于从变化的输入中获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆