26

Hello I need to sum the values of same class input in one input with class name total.

<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />

<input type="text" class="total" value="" />

Possible?

A working fiddle here

$(document).on("change", "qty1", function() {
    var sum = 0;
    $("input[class *= 'qty1']").each(function(){
        sum += +$(this).val();
    });
    $(".total").val(sum);
});
Paulo Boaventura
  • 1,195
  • 1
  • 8
  • 27
Andrei
  • 477
  • 1
  • 7
  • 17

9 Answers9

60

You pretty much had it, just needed to adjust your JQuery a little bit for the appropriate selectors

updated fiddle : http://jsfiddle.net/5gsBV/7/

$(document).on("change", ".qty1", function() {
    var sum = 0;
    $(".qty1").each(function(){
        sum += +$(this).val();
    });
    $(".total").val(sum);
});
Adjit
  • 9,708
  • 11
  • 49
  • 93
  • @Andrei not a problem! Anytime you want to access classes or id's in JQuery you have to be sure you include the `. or #` ie `.class` or `#id` – Adjit Jun 09 '14 at 19:01
  • thanks again, one more question http://jsfiddle.net/5gsBV/9/ how can I change "CHANGE" event on other so that it will sum the values even after page refresh? – Andrei Jun 09 '14 at 19:05
  • @Andrei I don't believe the value's will be saved in the text field on the page refresh. But this should take care of anytime the `qty` field is changed. – Adjit Jun 09 '14 at 19:35
  • Excellent Answer, the $("document").on(.....) also works to catch dynamically added HTML, which was my case. – David O'Regan Apr 08 '16 at 09:46
  • Thank you adjit you can also solve my problem in one my project in early morning. – Bhavin Thummar Jun 21 '17 at 04:47
  • @bhavinthummar absolutely! Have you posted a question? – Adjit Jun 21 '17 at 10:53
  • no @Adjit i have searched in google stakoverflow and i found your answer first and then my problem is solved. – Bhavin Thummar Jun 21 '17 at 11:05
  • @bhavinthummar ok good! If you have any questions just let me know – Adjit Jun 21 '17 at 11:06
  • Can someone please explain why do we use "`+`" just before `$(this).val();` in the function? – Kewal Shah Feb 03 '19 at 08:13
  • Ok I got it, it is a [unary](https://stackoverflow.com/a/17106702/8407719) operator – Kewal Shah Feb 03 '19 at 08:26
6

I suggest this solution:

html

<input type="text" class="qty1" value="" />
    <input type="text" class="qty1" value="" />
    <input type="text" class="qty1" value="" />
    <input type="text" class="qty1" value="" />
    <input type="text" class="qty1" value="" />
    <input type="text" class="qty1" value="" />

    <input type="text" class="total" value="" />

<div id="result"></div>

js

$(".qty1").on("blur", function(){
    var sum=0;
    $(".qty1").each(function(){
        if($(this).val() !== "")
          sum += parseInt($(this).val(), 10);   
    });

    $("#result").html(sum);
});

fiddle

Alex Char
  • 32,295
  • 8
  • 49
  • 69
2

I think your issue is here:

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

change it to:

$(".total").val(sum);

And instead of change event i suggest you to use keyup instead.

$(document).on("keyup"
Jai
  • 72,925
  • 12
  • 73
  • 99
2

$(document).on("keyup", ".qty1", function() {
    var sum = 0;
    $(".qty1").each(function(){
        sum += +$(this).val();
    });
    $(".total").val(sum);
});
1

We can use following own function

 (function( $ ){
   $.fn.sum=function () {
    var sum=0;
        $(this).each(function(index, element){
            sum += parseFloat($(element).val());
        });
    return sum;
    }; 
})( jQuery );
//Call $('.abcd').sum();

http://www.gleegrid.com/code-snippet/javascript/jquery-sum-input-values-by-class/?filter=bygroup&group=JQuery

PEHLAJ
  • 9,590
  • 9
  • 39
  • 51
1
$('.qty1').each(function(){
  sum += parseFloat(this.value);
   });
console.log(sum);
Rahman
  • 55
  • 1
  • 9
  • 1
    While the code might be easy to understand for people with experience, beginners might need an explanation. Please add an explanation what your code does and how it solves OPs question. – Max Vollmer Sep 28 '19 at 14:11
1

This will work with pure js

<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<p>Total Value :<span id="total">100%</span></p>
<p>Left Value :<span id="left">0.00%</span></p>
    var percenInput = document.querySelectorAll('.percent-input');
    for (let i = 0; i < percenInput.length; i++) {
        percenInput[i].addEventListener('keyup', getPercentVal)
    }

    function getPercentVal() {
        var total = 0;
        var allPercentVal = document.querySelectorAll('.percent-input');
        for (var i = 0; i < allPercentVal.length; i++) {
            if (allPercentVal[i].value > 0) {
                var ele = allPercentVal[i];
                total += parseFloat(ele.value);
            }
        }
        document.getElementById("total").innerHTML = total.toFixed(2) + '%';
        document.getElementById("left").innerHTML = (100 - total).toFixed(2) + '%';
    }
weirdan
  • 2,264
  • 21
  • 25
Rahul bind
  • 11
  • 2
0

You almost had it:

$(document).on("change", ".qty1", function() {
    var sum = 0;
    $(".qty1").each(function(){
        sum += +$(this).val();
    });
    $(".total").val(sum);
});

http://jsfiddle.net/DUKL6/1

0

The problem with all of the above answers is that they fail if you enter something other than a number. If you want something that is more friendly to users, you should do some validation, perhaps even give some feedback when a value other than a number is entered.

$('body').on('change', '.qty1', function() {
    var total=0;
    $(".qty1").each(function(){
        quantity = parseInt($(this).val());
        if (!isNaN(quantity)) {
            total += quantity;
        }
    });
    $('.total').val('Total: '+total);
});
jme11
  • 14,931
  • 2
  • 37
  • 46