简体   繁体   中英

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.

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".

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

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

$("#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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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