简体   繁体   English

使用jQuery对几个文本输入中的值求和

[英]Using jQuery to sum values from a couple text inputs

I have a couple of text inputs and I would like to compute the sum of the values in another input. 我有几个文本输入,我想计算另一个输入中值的总和。 This must happen on the fly, as soon as the user enters a value in one of the inputs. 一旦用户在其中一个输入中输入值,就必须即时进行此操作。 I'm planning to use jQuery for this, and I would like to add a class name for each input, something like class="input1", class="input2" and so on. 我打算为此使用jQuery,并且我想为每个输入添加一个类名,例如class =“ input1”,class =“ input2”等。

My problem is that I don't know to add all those values, and given the fact that I have over 50 inputs, I don't want to "add them by hand". 我的问题是我不知道将所有这些值相加,并且鉴于我有50多个输入,我不想“手工添加”。

Any kind of help is appreciated. 任何帮助都将受到赞赏。

If you decorate all of the inputs you want added together with classes of input1 , input2 , and so on, this will get the sum of the current values in all those inputs 如果您装饰所有要添加的输入以及input1input2等类,则将获得所有这些输入中当前值的总和

var sum = 0;

$("input[class *= 'input']").each(function(){
    sum += +$(this).val();
});

Then naturally if you want to put this value in an input of id destination 然后自然地,如果您想将此值放入id destination的输入中

$("#destination").val(sum);

Here's a fiddle 这是一个小提琴

EDIT 编辑

If you want this to run whenever any of these textboxes are changed , then you can put this in a change event handler 如果要在任何这些文本框发生更改时都运行此命令,则可以将其放在更改事件处理程序中

$(document).on("change", "input[class *= 'input']", function() {
    var sum = 0;

    $("input[class *= 'input']").each(function(){
        sum += +$(this).val();
    });

    $("#destination").val(sum);
});

Here's that fiddle 这是小提琴

EDIT 编辑

Per Jaspers comment, if you know that input1 , input2 , etc, will always be the first class on your inputs, ie, you'll never do 根据Jaspers的评论,如果您知道input1input2始终是您输入中的第一类,即您永远不会

<input class='someNewClass input1'

then you could 那你可以

$("input[class ^= 'input']").each(function(){

^= means starts with, while *= means contains anywhere. ^=表示以开头,而*=表示包含任何位置。

give them a common name and you need to parse the value since it will be text initially 给他们一个通用名称,您需要解析该值,因为最初它是文本

var result= 0;

$("input[name='sum']").each(function(){
    result = result + parseInt($(this).val(),10);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM